2011-03-05 51 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