Is there a way to create a function from a string with javascript?

For example:

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

If it's a string, I need a function called fnc. And fnc(); A warning screen appears.

eval("alert(1);") does not solve my problem.

+66
javascript function string
04 Oct 2018-11-11T00:
source share
7 answers

The best way to create a function from a string is Function :

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

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

Arguments are also possible:

 var addition = Function("a", "b", "return a + b;"); alert(addition(5, 3)); // shows '8' 
+143
04 Oct 2018-11-11T00:
source share
— -

You are 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 .

+36
04 Oct 2018-11-11T13
source share

I added the jsperf test for 4 different ways to create a function from a string:

  • Using RegExp with the Function Class

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

  • Using the Function class with "return"

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

  • Using the 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 results: enter image description here enter image description here

+29
Jan 18 '15 at 15:16
source share

JavaScript dynamic function names

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' 
+11
Dec 09 '13 at 14:49
source share

Yes, using Function is a great solution, but we can go a little further and prepare a universal parser that parses the string and converts it into a 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 using:

 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

+11
Nov 13 '14 at 20:37
source share

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

 var newCode = document.createElement("script"); newCode.text = "function newFun( a, b ) { return a + b; }"; document.body.appendChild( newCode ); 

This functionally resembles adding this <script> element to the end of your document, for example:

 ... <script type="text/javascript"> function newFun( a, b ) { return a + b; } </script> </body> </html> 
+5
Jan 19 '15 at 6:41
source share

An example with dynamic arguments:

 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])) 
0
Oct 30 '17 at 1:16
source share



All Articles