有没有办法用javascript从字符串创建一个函数?

问题描述 投票:86回答:8

例如;

var s = "function test(){
  alert(1);
}";

var fnc = aMethod(s);

如果这是字符串,我想要一个名为fnc的函数。并且fnc();弹出警报屏幕。

qazxsw poi并没有解决我的问题。

javascript string function
8个回答
46
投票

我添加了一个jsperf测试,用于从string创建函数的4种不同方法:

  • 将RegExp与Function类一起使用 eval("alert(1);")
  • 使用带有“返回”的Function类 var func = "function (a, b) { return a + b; }".parseFunction();
  • 使用官方Function构造函数 var func = new Function("return " + "function (a, b) { return a + b; }")();
  • 使用Eval var func = new Function("a", "b", "return a + b;");

eval("var func = function (a, b) { return a + b; };");

2结果样本:http://jsben.ch/D2xTG enter image description here


162
投票

从字符串创建函数的更好方法是使用enter image description here

Function

这具有优点/缺点,即当前范围中的变量(如果不是全局的)不适用于新构造的函数。

传递参数也是可能的:

var fn = Function("alert('hello there')");
fn();

37
投票

你很亲密。

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();


13
投票

是的,使用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


11
投票

Dynamic function names in here

使用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'

使用http://marcosc.com/2012/03/dynamic-function-names-in-javascript/

eval

使用var name = "foo"; // Implement it eval("function " + name + "() { alert('Foo'); };"); // Test it foo(); // Next is TRUE foo.name === 'foo'

sjsClass

Example

https://github.com/reduardo7/sjsClass

5
投票

这种技术可能最终等同于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 );

2
投票

使用带有返回值的... <script type="text/javascript"> function newFun( a, b ) { return a + b; } </script> </body> </html> 并立即执行。

new Function()

0
投票

动态参数的示例:

var s = `function test(){
  alert(1);
}`;

var new_fn = new Function("return " + s)()
console.log(new_fn)
new_fn()
© www.soinside.com 2019 - 2024. All rights reserved.