Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call anonymus function from string

I have string containg anonymus function definition, but how i can call this. Lets say function is like so:

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

Tried eval, but got an error that function must have a name.

eval(fn_str).apply(this); // SyntaxError: function statement requires a name
like image 918
Kristian Avatar asked Mar 09 '12 08:03

Kristian


2 Answers

You can use Immediately Invoked Function Expression:

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

Immediately Invoked Function Expression

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

var func = new Function("alert('called')");
func.apply(this);
like image 156
gdoron is supporting Monica Avatar answered Oct 17 '22 19:10

gdoron is supporting Monica


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

like image 22
steveukx Avatar answered Oct 17 '22 19:10

steveukx