谁能帮我理解为什么 new Function 在这里不起作用?
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
我的语法有问题吗?
最佳答案
您对 foo() 的调用只是返回函数对象,而不是调用它。试试这个:
foo()();
关于来自 String 的 Javascript 函数构造函数无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5403282/