2011-03-23 120 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