[英]Is it possible to roll your own 'function' construct or 'eval' method in javascript?
Is it at all possible to re-implement 'function' or 'eval' in pure javascript? 是否有可能在纯JavaScript中重新实现“功能”或“评估”? Eg lets say I wanted to be able to write the following: 例如,可以说我希望能够编写以下内容:
// note that I don't want to have to put code in a string here
var x = func() { var something = "nothing"; return something; }
or 要么
var hiString = 'hi' // note that it of course needs to be able to access the current context
evaluatize("function hi(){ alert(hiString); } hi();")
Are either of these things possible in javascript? javascript是否有上述两种可能?
您可以使用类似Narcissus的JavaScript编写JavaScript解释器。
for the first, I'm not sure if you were asking something different, but this works: 首先,我不确定您是否要提出不同的要求,但这是可行的:
var x = function() {return "cake";}
x();
不,这是不可能的。
If your needs are simple, then you can do something like this: 如果您的需求很简单,那么可以执行以下操作:
var generator = function(input) {
return function() {alert(input)};
};
var helloFunction = generator("Hello, World.");
helloFunction(); // alerts "Hello, World."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.