Is there a way to create a function from a string

2019-01-03 04:46发布

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.

8条回答
在下西门庆
2楼-- · 2019-01-03 05:19

You're pretty close.

//Create string representation of function
var s = "function test(){  alert(1); }";

//"Register" the function
eval(s);

//Call the function
test();

Here's a working fiddle.

查看更多
地球回转人心会变
3楼-- · 2019-01-03 05:20

This technique may be ultimately equivalent to the eval method, but I wanted to add it, as it might be useful for some.

var newCode = document.createElement("script");

newCode.text = "function newFun( a, b ) { return a + b; }";

document.body.appendChild( newCode );

This is functionally like adding this <script> element to the end of your document, e.g.:

...

<script type="text/javascript">
function newFun( a, b ) { return a + b; }
</script>

</body>
</html>
查看更多
The star\"
4楼-- · 2019-01-03 05:30

Yes, using Function is a great solution but we can go a bit further and prepare universal parser that parse string and convert it to real 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;
    };
}

examples of usage:

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

here is jsfiddle

查看更多
ら.Afraid
5楼-- · 2019-01-03 05:30

Dynamic function names in JavaScript

Using 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'

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

Using eval

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

Using sjsClass

https://github.com/reduardo7/sjsClass

Example

Class.extend('newClassName', {
    __constructor: function() {
        // ...
    }
});

var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
查看更多
何必那么认真
6楼-- · 2019-01-03 05:35

A better way to create a function from a string is by using Function:

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

This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.

Passing arguments is possible too:

var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
查看更多
三岁会撩人
7楼-- · 2019-01-03 05:37

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; };");

http://jsben.ch/D2xTG

2 result samples: enter image description here enter image description here

查看更多
登录 后发表回答