Changing a string to a function in javascript (not eval)

var foo = "function (){ alert('meee'); }"; foo(); 

I tried above, but it does not work, is there any other way to execute this function without using eval?

Thnx

+6
javascript function string
source share
3 answers

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(); // alerts "meee" 

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(); // eval: 15, 34 // Func: haha, hehe 

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.

+8
source share

According to MDC . Using:

 var multiply = new Function("x", "y", "return x * y"); var theAnswer = multiply(7, 6); 
+3
source share

not what I know ... probably the best way to do what you are trying to do without making yourself vulnerable to an attack on a script that doesn't include passing around javascript as a string.

0
source share

All Articles