Suppose I have a variable that contains the name of a function I want to run, I can run it by using window
, like so;
var func = "myFunc",
myFunc = function(){ ... };
window[func](); // run the function in the func var
However, this doesn't work if the intended function is deep inside an object;
var obj = {
foo: {
hey: function(){ ... }
}
};
obj.foo.hey(); // this runs
var func = "obj.foo.hey";
window[func](); // this doesn't
I could use eval()
, but I wonder if it's possible to avoid that, so as to not introduce the many security considerations that eval()
comes with.
How can I run a function specified in a variable, when the function is in an object as described above?