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,283
  • 3
  • 28
  • 52

3 Answers3

8

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
  • 147,333
  • 58
  • 291
  • 367
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,370
  • 19
  • 27
1

Found the solution: Put function in parentheses

var a = "(function(){ alert('called'); })";
eval(a).apply(this);
Kristian
  • 3,283
  • 3
  • 28
  • 52
  • 1
    You don't need to write use `apply` you can use *Immediately Invoked Function Expressions** as I answered. – gdoron Mar 09 '12 at 08:29
  • I know that syntax, but i cant pass an object as a parameter that way(without parsing an object to string). Or can i? – Kristian Mar 09 '12 at 08:34
  • What did you mean in that comment, I didn't understand it. What do you need? – gdoron Mar 09 '12 at 09:06
  • Sample code: `var fn = "function(object, cb) { /* Do something with the object */ }"; var obj = { param: value, param2: value2 }; eval('('+fn')').apply(this, [obj]);` – Kristian Mar 09 '12 at 09:10
  • Can you get the function body? without the `function(object, cb){ ` part – gdoron Mar 09 '12 at 09:13
  • I could if i'll parse the string and strip `function(){` and `}` from it, but i alrealy solved my case. Thanks anyways – Kristian Mar 09 '12 at 09:16