Search code examples
javascripteval

executing anonymous functions created using JavaScript eval()


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.


Solution

  • 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'