开发者

Javascript Function Constructor from String failes to run

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 (开发者_如何学Go) {anotherFunctionToRun();}; }
alert(foo()) // function () { anotherFunctionToRun(); }

foo(); // Wont do anything

Is there something wrong with my syntax?


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

foo()();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜