Search code examples
javascriptstringfunction

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 this is the string, I want a function that's called fnc. And fnc(); pops alert screen.

eval("alert(1);") doesnt solve my problem.


Solution

  • 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