来自String的Javascript函数构造函数无法运行

时间:2011-03-23 09:43:31

标签: javascript string 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

我的语法有问题吗?

2 个答案:

答案 0 :(得分:2)

你对foo()的调用只是返回函数对象,而不是调用它。试试这个:

FOO()();

答案 1 :(得分:0)

您正在创建foo作为返回另一个函数的函数。无论何时执行foo(),它都会返回一个函数。

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

要运行anotherFunctionToRun,您需要执行返回的函数:

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

或者只是不要将data["callback"]代码包装在函数返回函数中以开始。