例如;
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
如果这是字符串,我想要一个名为fnc的函数。并且fnc();
弹出警报屏幕。
qazxsw poi并没有解决我的问题。
我添加了一个jsperf测试,用于从string创建函数的4种不同方法:
eval("alert(1);")
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; };");
2结果样本:http://jsben.ch/D2xTG
你很亲密。
var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
这是//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
。
是的,使用a working fiddle是一个很好的解决方案,但我们可以更进一步,准备解析字符串并将其转换为真正的JavaScript函数的通用解析器...
Function
用法示例:
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
JavaScript
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
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
这种技术可能最终等同于eval方法,但我想添加它,因为它可能对某些人有用。
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
这在功能上就像将<script>元素添加到文档的末尾,例如:
var newCode = document.createElement("script");
newCode.text = "function newFun( a, b ) { return a + b; }";
document.body.appendChild( newCode );
使用带有返回值的...
<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()