How to call anonymus function from a string

I have a function definition for an anonymous string, but what can I call it. Assume a function like this:

var fn_str = "function(){ alert('called'); }";

I tried eval, but got an error that the function must have a name.

eval(fn_str).apply(this); // SyntaxError: function statement requires a name
+5
source share
3 answers

You can use Expression Exposed Expression Expression:

var fn_str = "function(){ alert('called'); }";
eval('(' + fn_str +')();');

Instant call function expression

Another way is to use an object Function(if you have a function body string):

var func = new Function("alert('called')");
func.apply(this);
+5
source

You can create functions from strings using the Function constructor:

var fn = new Function("arg1", "alert('called ' + arg1);");
fn.apply(this)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

+3
source

:

var a = "(function(){ alert('called'); })";
eval(a).apply(this);
+1

All Articles