you want to use the Function constructor directly, as Anders said. All arguments are strings. The last argument is the body of the function, any leading arguments are the names of the arguments that the function takes.
To borrow from Andersโs example,
var multiply = new Function("x", "y", "return x * y");
will be like a record
var multiply = function (x,y) { return x * y }
In your case, you have "function (){ alert('meee'); }" and you want to save it as a function for var foo .
var fn = "function (){ alert('meee'); }"; var foo = new Function("return ("+fn+")")(); foo();
The difference between Function and eval is eval is performed in the private area, and Function is executed in the global area.
var x="haha", y="hehe"; function test () { var x=15, y=34; eval("alert('eval: ' + x + ', ' + y)"); new Function("alert('Func: ' + x + ', ' + y)")(); } test();
Do not try to run it in the console, you will get a deceptive result (the console uses eval ). Writing it to the <script> and loading it in the browser will give the correct result.
Dagg nabbit
source share