Get JavaScript function-object from its name as a string?

Viewed 50698

In JavaScript, if I have a string in a variable, is there a way to get a reference to the function object which has that matching name? Note that jQuery is available to me so I can use any of its helper methods also.

For example:

myFunction = function(){};

var func_name = "myFunction";
var myFunctionPtr = ???  //how to get the function from the name

Thanks

9 Answers

if you know that its a global function you can use:

var functPtr = window[func_name];
//functPtr()

Otherwise replace window with the parent object containing the function.

I just did a quick test in Firebug and I was able to get the function from the name by simply eval()ing the name... I feel dirty using eval(), but it seems to get the job done here quite nicely.

var myFunctionPtr = eval(func_name);

this[func_name] should give you the function.

var myfunc = this[func_name];
myfunc();

A safe way to do is to sandbox the alleged function while testing its type:

function isFunction(expr) {
    function sandboxTemplate() {
        var window, document, alert; // etc.

        try {
            return typeof $expr$ == "function";
        } catch (e) {
            return false;
        }
    }

    try {
        var sandbox = new Function(
            sandboxTemplate.toString().replace("$expr$", expr)
            + "return sandboxTemplate()");
        return sandbox();
    } catch (e) {
        return false;
    }
}

function test(expr) {
    document.write("<div>\"" + expr + "\" <b>is "
        + (isFunction(expr) ? "" : "not ")
        + "</b>a function</div>");
}

/* Let's do some testing */

function realFunction() {
}

test("realFunction");       // exists!
test("notHere");            // non-existent
test("alert('Malicious')"); // attempt to execute malicious code!
test("syntax error {");     // attempt to blow us up!

The output:

  • "realFunction" is a function
  • "notHere" is not a function
  • "alert('Malicious')" is not a function
  • "syntax error {" is not a function

The sandboxing code could be written in a more concise manner but I like using "template" functions instead of embedding JS code as string literals.

And oh, this does it nicely without using eval -- though one can argue that using a Function constructor is no different than an eval.

Use eval:

myFunction = function(){};

var func_name = "myFunction";
var myFunctionPtr = eval(func_name);
Related