Skip to content Skip to sidebar Skip to footer

Changing String To A Function In Javascript (not Eval)

var foo = 'function (){ alert('meee'); }'; foo(); I have tried the above but it does not work is there any other way to execute that function without using eval? thnx

Solution 1:

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 the function takes.

To borrow from Anders' example,

var multiply = newFunction("x", "y", "return x * y");

would be like writing

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 to var foo.

var fn = "function (){ alert('meee'); }";
var foo = newFunction("return ("+fn+")")();
foo();
// alerts "meee"

The difference between Function and eval is eval runs in the private scope, while Function runs in the global scope.

var x="haha", y="hehe";

functiontest () {
  var x=15, y=34;
  eval("alert('eval: ' + x + ', ' + y)");
  newFunction("alert('Func: ' + x + ', ' + y)")();
} 

test();

// eval: 15, 34// Func: haha, hehe

Don't try to run it in the console, you'll get a deceiving result (consoles use eval). Writing it in a <script> tag and loading it in the browser will give the true result.

Solution 2:

According to MDC. Use:

var multiply = newFunction("x", "y", "return x * y");
var theAnswer = multiply(7, 6);

Solution 3:

not that I know of... there's probably a better way to do what you're trying to do without making yourself vulnerable to a script injection attack that doesn't involve passing around javascript as a string.

Solution 4:

example js code in string

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

var F=newFunction (theInstructions);

F.apply(null)

Post a Comment for "Changing String To A Function In Javascript (not Eval)"