2011-03-05 50 views
0

是否有可能在純JavaScript中重新實現'function'或'eval'?例如。可以說,我希望能寫:是否有可能在JavaScript中推出自己的'函數'構造或'eval'方法?

// note that I don't want to have to put code in a string here 
var x = func() { var something = "nothing"; return something; } 

var hiString = 'hi' // note that it of course needs to be able to access the current context 
evaluatize("function hi(){ alert(hiString); } hi();") 

在javascript要麼這些事情可能嗎?

回答

0

不,這是不可能的。

+0

這樣的聲音就是答案.. – 2011-03-05 23:38:32

4

您可以使用JavaScript編寫JavaScript解釋器,如Narcissus

+0

如果您選擇這種方法,可能會讓翻譯人員能夠供應咖啡,但編程時喝杯咖啡總是有用的! – krtek 2011-03-05 20:12:40

+0

+1水仙花,但應該注意,將只適用於使用蜘蛛猴的Firefox和應用程序 – 2011-03-05 20:47:17

+0

哈哈,以及我希望我可以直接在js做到這一點 – 2011-03-05 21:13:16

1

爲先,我不知道,如果你問不同的東西,但這個工程:

var x = function() {return "cake";} 
x(); 
+0

對於第二,只需使用JavaScript的'eval()'函數即可。 – 2011-03-05 20:19:54

0

如果您的需求很簡單,那麼你可以做這樣的事情:

var generator = function(input) { 
    return function() {alert(input)}; 
}; 

var helloFunction = generator("Hello, World."); 

helloFunction(); // alerts "Hello, World." 
+0

他們不是那麼簡單 – 2011-03-05 21:14:35