2011-03-23 84 views
1

有人可以帮我理解为什么新函数在这里不起作用吗?Javascript函数构造函数从字符串失败运行

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 

我的语法有问题吗?

回答

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"]代码。

+0

感谢您的快速响应,此工作。 – Gomer 2011-03-23 09:59:52

2

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

foo()();

+0

这也有效,感谢您的快速响应。 – Gomer 2011-03-23 10:00:16