views:

416

answers:

5

I have a function and its contents as a string.

var funcStr = "function() { alert('hello'); }";

Now, I do an eval() to actually get that function in a variable.

var func = eval(funcStr);

If I remember correctly, in Chrome and Opera, simply calling

func();

invoked that function and the alert was displayed.

But, in other browsers it wasn't the case. nothing happened.

I don't want an arguement about which is the correct method, but how can I do this? I want to be able to call variable(); to execute the function stored in that variable.

+2  A: 

Try

var funcStr = "var func = function() { alert('hello'); }";

eval(funcStr);

func();
djch
hey, Thanks that worked! But it looks a bit weird to do it that way :D.
+1  A: 

Use the eval like this :

var func = eval('(' + funcStr + ')');
Andreas Grech
That's what I thought initially, but I'm pretty sure that applies only to objects.
karim79
Also, whether its the right way or the wrong way..., it doesn't work in IE.
Functions are objects too. It works with parentheses.
Blixt
+4  A: 

How about this?

var func = new Function('alert("hello");');

To add arguments to the function:

var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world

Do note that functions are objects and can be assigned to any variable as they are:

var func = function () { alert('hello'); };
var otherFunc = func;
func = 'funky!';

function executeSomething(something) {
    something();
}
executeSomething(otherFunc); // Alerts 'hello'
Blixt
This is both an elegant way to do it, and works in all browsers. Thanks :)
+2  A: 

IE cannot eval functions (Presumably for security reasons).

The best workaround is to put the function in an array, like this:

var func = eval('[' + funcStr + ']')[0];
SLaks
Heh... Sneaky sneaky!
Blixt
A: 

What also works is

var myFunc = function(myParam){
   // function body here
}
Zoidberg