0

Can it be done?

I have the following:

populate.func = function(node, state) {
    return (new function(data) { /* stuff*/ });
}

However, calling populate.func invariably calls both the called function and the returned function, whether I use regular calling convention or the call method. I want to be able to call populate.func and just return the function as a value to make use of, without actually running it...

4
  • why new? it should work without it. i mean, say infunc = function(data){ /* stuff*/ }; You do: return infunc; Commented Aug 7, 2012 at 6:03
  • You want to return the function as a string? Commented Aug 7, 2012 at 6:03
  • New because I read that this was a trick to pass a function by reference and pass variable in the state it was in when you passed the function as an argument, and not when it gets called. I think it does this because so long as a pointer is maintained to the child function, the parent can't be garbage collected either, nor its call stack. Or something. Commented Aug 7, 2012 at 6:09
  • @RobF you have been terribly misinformed, go read up some more on javascript... Commented Aug 7, 2012 at 6:10

2 Answers 2

1

just do this

populate.func = function(node, state) {
    return (function(data) { /* stuff*/ });
}

Your code is instantiating a new object using your function as a constructor function, but you want to return a reference to your function instead, so just drop the new keyword.

Sign up to request clarification or add additional context in comments.

6 Comments

That seems to have worked. Will wait and experiment a bit before leaving feedback. Why did new operator cause it to call both functions?
because you executed the function to instantiate an object from it, using the function as a constructor function.
That doesn't answer the question.
@RobF It does, that is exactly the reason why it calls the function. You should read up on what new does in JS.
@RobF do you feel like you understand what i tried to say or is it still unclear ?
|
0

I'm not even sure what your code is actually doing, but I think what you want is:

populate.func = function(node, state) {
    return function(data) { /* stuff*/ };
}

2 Comments

@RobF adding in new doesn't make any diffrence there, you are returning an object by reference, instantiated by your constructor function, but not the function it self.
return function... will return a reference to the function w/o executing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.