开发者

Javascript Function Constructor from String failes to run

开发者 https://www.devze.com 2023-02-19 17:31 出处:网络
Could someone help me understand why new Function does not work here? var fn = data[\"callback\"]; // String with value: function() { anotherFunctionToRun(); }

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

精彩评论

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

关注公众号