Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a javascript function that's a member of an object by name

Tags:

javascript

I want to be able to pass a reference to an arbitrary function by name to another javascript function. If it's just a global function, there is no problem:

function runFunction(funcName) {
   window[funcName]();
}

But suppose the function could be a member of an arbitrary object, e.g.:

object.property.somefunction = function() {
 //
}

runFunction("object.property.somefunction") does not work. I know I can do this:

window["object"]["property"]["somefunction"]()

So while could write code to parse a string and figure out the heirarchy this way, that seems like work :) So I wondered if there's any better way to go about this, other than using eval()

like image 606
Jamie Treworgy Avatar asked Jan 20 '23 07:01

Jamie Treworgy


1 Answers

You can call funcName.split('.') and loop through the resulting array, like this:

function runFunction(funcName) {
    var parts = funcName.split('.');
    var obj = window;

    for (var i = 0; i < parts.length; i++)
        obj = obj[parts[i]];

    return obj();
}
like image 151
SLaks Avatar answered Jan 22 '23 20:01

SLaks