1

Could someone help me understand why new Function does not work here?

var fn = data["callback"]; // String with value: function() { anotherFunctionToRun(); }
var foo = new Function("return ("+fn+")");
foo();

alert(foo) // returns function anonymous() { return function () {anotherFunctionToRun();}; }
alert(foo()) // function () { anotherFunctionToRun(); }

foo(); // Wont do anything

Is there something wrong with my syntax?

2 Answers 2

2

Your call to foo() is just returning the function object, but not invoking it. Try this:

foo()();

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

Comments

0

You're creating foo as a function which returns another function. Whenever you execute foo(), it'll return a function.

foo(); // returns a function, but appears to do nothing

alert(foo) // prints definition of foo, which is the complete function body
alert(foo()) // shows you the function body of the function returned by foo

foo(); // returns a function, but appears to do nothing

To run anotherFunctionToRun, you would need to execute the returned function:

var anotherFoo = foo();
anotherFoo(); // should execute anotherFunctionToRun

Or just don't wrap the data["callback"] code in a function returning function to begin with.

Comments

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.