ymutlu ymutlu - 4 months ago 14
Javascript Question

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

For example;

var s = "function test(){

var fnc = aMethod(s);

If this is the string, I want a function that's called fnc. And
pops alert screen.

doesnt solve my problem.


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

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

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'