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()
Nope — other than using
evalI do not know another way of walking down an object tree in JavaScript than to build a walker — fortunately, it is easy to do:Then just call it like so: