[英]Dynamically creating static variables in a javascript function
How does one go about dynamically creating a function in javascript, but have a variable be "dynamically hardcoded" (?). 如何在javascript中动态创建函数,但如何对变量进行“动态硬编码”(?)。 Preferably without using eval() . 最好不使用eval() 。
I thought this would be the cleanest way to pass async.parallel() a few parameters in nodejs without having to bind objects. 我认为这是在不绑定对象的情况下在nodejs中传递async.parallel()一些参数的最干净的方法。
function makeFunction( param1){
return function(){
alert(param1);
}
}
Actual Output from console.log( makeFunction("Hello World") ); console.log(makeFunction(“ Hello World”))的实际输出;
return function(){ alert(param1); }
Desired Output from console.log( makeFunction("Hello World") ); 来自console.log(makeFunction(“ Hello World”))的所需输出;
return function(){ alert("Hello World"); }
function makeFunction(param1){
return new Function('alert(\'' + param1 + '\');')
}
console.log(makeFunction('helloWorld').toString())
only like that. 只是那样 new Function
is a little bit "evaly" but in fact it's much better (or less evil). new Function
有点“逃避”,但实际上它更好(或更少邪恶)。
I don't feel it'd be better than using eval
, but probably this would be what you want: 我觉得这比使用eval
更好,但是这可能就是您想要的:
function makeFunction(param1) {
var F=function () {
alert(param1);
};
var text=['"', '"'].join(param1);
text=String.prototype.replace.call(F, 'param1', text);
text=['return ', ';'].join(text);
return (new Function(text))();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.