var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
如果这是字符串,我想要一个名为 fnc 的函数。并且 fnc();
会弹出警示框。
eval("alert(1);")
不能解决我的问题。
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
如果这是字符串,我想要一个名为 fnc 的函数。并且 fnc();
会弹出警示框。
eval("alert(1);")
不能解决我的问题。
使用 Function
是创建函数的更好方法:
var fn = Function("alert('hello there')");
fn();
这样做的优点/缺点是,当前范围内的变量(如果不是全局的)不适用于新构建的函数。
也可以传递参数:
var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
我添加了一个 jsperf 测试,测试了四种不同的从字符串创建函数的方式:
使用 Function 类和 RegExp
var func = "function (a, b) { return a + b; }".parseFunction();
使用带 "return" 的 Function 类
var func = new Function("return " + "function (a, b) { return a + b; }")();
使用官方 Function 构造器
var func = new Function("a", "b", "return a + b;");
使用 Eval
eval("var func = function (a, b) { return a + b; };");
你非常接近了。
//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
这里是一个有效的fiddle。
eval
警告:eval
可能会为黑客打开漏洞。但如果你知道它的危险并能避免它们,那么这是一种从字符串创建函数的不错而简单的方法。参考链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval - user993683是的,使用Function
是一个很好的解决方案,但我们可以更进一步,准备一个通用解析器,将字符串解析并转换为真正的JavaScript函数...
if (typeof String.prototype.parseFunction != 'function') {
String.prototype.parseFunction = function () {
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(this.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
使用示例:
var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));
func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();
这里是 jsfiddle
Function
var name = "foo";
// Implement it
var func = new Function("return function " + name + "(){ alert('hi there!'); };")();
// Test it
func();
// Next is TRUE
func.name === 'foo'
eval
来源:http://marcosc.com/2012/03/dynamic-function-names-in-javascript/
var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'
sjsClass
https://github.com/reduardo7/sjsClass
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
这种技术可能最终等同于eval方法,但我想加入它,因为它对某些人可能有用。
var newCode = document.createElement("script");
newCode.text = "function newFun( a, b ) { return a + b; }";
document.body.appendChild( newCode );
这个功能类似于将以下 <script> 元素添加到文档末尾:
...
<script type="text/javascript">
function newFun( a, b ) { return a + b; }
</script>
</body>
</html>
使用带有返回值的new Function()
,并立即执行它。
var s = `function test(){
alert(1);
}`;
var new_fn = new Function("return " + s)()
console.log(new_fn)
new_fn()
一个带有动态参数的例子:
let args = {a:1, b:2}
, fnString = 'return a + b;';
let fn = Function.apply(Function, Object.keys(args).concat(fnString));
let result = fn.apply(fn, Object.keys(args).map(key=>args[key]))
new Function
的字符串中包含一个返回语句。const strFn = "const sum = (a, b) => a + b"
const newFn = new Function(`${strFn}; return sum`)();
console.log(newFn(2, 3)) // 5
如果您不想立即执行,可以使用 function.call
方法来执行。请记住它所接受的第一个参数是 this
值。
const newFn = new Function('const arrMultiplier = (arr) => arr.map(num => num * 2); return arrMultiplier')
console.log(newFn.call({}).call({}, [6, 4, 1, 0])); // [12, 8, 2, 0]
var parseFunction = (stringFunction_)=>{
eval('var tempFunction = ' + stringFunction_);
return tempFunction;
}
var func = parseFunction('(a,b) =>{return a + b;}');
func(2,2)
//it will return 4
Function
可以避免污染本地作用域,这也是为什么eval
对引擎的优化造成困难的原因...针对原帖的示例,我会这样做:var fnc = Function('return '+s)();
- Christian C. Salvadóelement.onclick = function() { alert("test"); }
。 - Lekensteyn