有没有办法用javascript从字符串创建函数? [英] Is there a way to create a function from a string with javascript?
问题描述
例如;
var s = "function test(){警报(1);}";var fnc = aMethod(s);
如果这是字符串,我想要一个名为 fnc 的函数.并且 fnc();
弹出警告屏幕.
eval("alert(1);")
没有解决我的问题.
我添加了一个 jsperf 测试,用于从字符串创建函数的 4 种不同方法:
在函数类中使用 RegExp
var func = "function (a, b) { return a + b; }".parseFunction();
使用带有返回"的函数类
var func = new Function("return " + "function (a, b) { return a + b; }")();
使用官方函数构造器
var func = new Function("a", "b", "return a + b;");
使用评估
eval("var func = function (a, b) { return a + b; };");
For example;
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
If this is the string, I want a function that's called fnc. And fnc();
pops alert screen.
eval("alert(1);")
doesnt solve my problem.
I added a jsperf test for 4 different ways to create a function from string :
Using RegExp with Function class
var func = "function (a, b) { return a + b; }".parseFunction();
Using Function class with "return"
var func = new Function("return " + "function (a, b) { return a + b; }")();
Using official Function constructor
var func = new Function("a", "b", "return a + b;");
Using Eval
eval("var func = function (a, b) { return a + b; };");
2 result samples:
这篇关于有没有办法用javascript从字符串创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!