2011-03-23 7 views
1

새로운 기능이 여기에서 작동하지 않는 이유를 아는 사람이 있습니까?Javascript 함수 String에서 생성자가 실행되지 않습니다.

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()을 실행할 때마다 함수가 반환됩니다. anotherFunctionToRun 실행하려면

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 

, 당신은 반환 된 기능을 실행해야합니다 :

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

또는 단지로 시작하는 기능을 반환하는 함수에서 data["callback"] 코드를 포장하지 않습니다.

+0

빠른 응답을 보내 주셔서 감사합니다. – Gomer

2

foo()를 호출하면 함수 객체가 반환되지만 호출되지는 않습니다. 이것을 시도하십시오 :

foo()();

+0

빠른 응답을 보내 주셔서 감사합니다. – Gomer

관련 문제