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

ymutlu picture ymutlu · Oct 4, 2011 · Viewed 69k times · Source

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.

Answer

Lekensteyn picture Lekensteyn · Oct 4, 2011

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'