6

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
Kristian
  • 3,047
  • 1
  • 20
  • 45

3 Answers3

6

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);
Community
  • 1
  • 1
gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
3

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

steveukx
  • 4,242
  • 18
  • 26
1

Found the solution: Put function in parentheses

var a = "(function(){ alert('called'); })";
eval(a).apply(this);
Kristian
  • 3,047
  • 1
  • 20
  • 45