executing anonymous functions created using JavaScript eval()

I realize this is old, but it was the only valid result coming up in my google searches for evaluating anonymous javascript function strings.

I finally figured out how to do it from a post on the jquery google group.

eval("false||"+data)

where data is your function string like "function() { return 123; }"

So far, I have only tried this in IE8 and FF8 (the browsers on my personal computer), but I believe jquery uses this internally so it should work just about everywhere.


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];

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'

Try

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

eval(funcStr);

func();