ymutlu ymutlu - 1 year ago 57
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.

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download