有没有一种方法可以在不使用 eval() 的情况下在运行时使用设计时未知(但可信)的内容创建函数?
基本上,出于性能原因,我正在尝试创建一个“硬编码”函数,因为它将被调用很多次。 在许多调用开始之前,只有“硬编码”会在运行时完成一次。
(未经测试的例子)
var strFuncString = 'function(){';
for (some loop)
{
strFuncString+='DoSomething()'; //if this can be made to reference an object obtained for the for-loop then even better - i.e. Myfunc+=Obj.DoSomething
}
var MyFunc = eval(strFuncString '}');
SomeProcessThatCallsItsArgALot(MyFunc);
我在调试器中试过了,但不出所料,它不起作用
((function(){console.log(1);} )+( function(){console.log(2);}))()
最佳答案
您可以使用new Function(bodytext)
。
参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
关于javascript - 在运行时创建一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16937975/