ymutlu ymutlu - 1 month ago 7
Javascript Question

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.

Answer

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