如何在不使用 eval 的情况下调用如下所示的粗箭头函数(存储在字符串中)?
"g => { alert(g); }"
使用 eval 时,下面的代码工作正常,但我想避免使用 eval。
eval("g => { alert(g); }")('hello')
我希望我可以使用“new Function”做类似下面的事情,但到目前为止我还没有运气。
new Function("g => { alert(g); }")('hello')
提前非常感谢。
最佳答案
来自MDN
The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and performance issues similar to eval.
也就是说,您可以轻松解析字符串以使用函数构造函数,例如:
const str = [g,body] = "g => { console.log(g); }".split(" => ");
var myFunc = new Function(g, body);
myFunc("hello");
const str2 = [args,body] = "(h,i) => {console.log(h,i);}".split(" => ");
const [h,i] = args.replace(/\(|\)/g,"").split(",");
var myFunc2 = new Function(h,i, body);
myFunc2("hello","buddy");
关于javascript - 如何在不使用 eval 的情况下调用存储在字符串中的胖箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49287658/