Yeah, there are numerous questions like How to turn a String into a javascript function call? or How to execute a JavaScript function when I have its name as a string.
But what if we have not a plain function name, but an object property name which in fact is a function?
Like:
var callMe = 'foo.bar.baz';
and the code expected to be called is:
window.foo = {
bar: {
baz: function() {
alert('Eureka!');
}
}
};
Why I need this: the callback parameter is passed via url and it can (by application design) be either a function name or FQN of object's property.
Any ideas others than eval()?
UPD:
My final implementation:
var parts = callbackName.split('.'),
callback;
for (i in parts) {
if (!callback) {
callback = window[parts[i]];
} else {
callback = callback[parts[i]];
}
if (typeof callback === 'undefined') break;
}
if (typeof callback === 'function') {
callback();
} else {
console.error('Passed callback is not a valid function');
}
try
window['foo']['bar']['baz']()
If this works for you, should be easy to translate 'foo.bar.baz' into that.
See the code below and check out the fiddle ( http://jsfiddle.net/bxsHp/ ) :
window.foo = {
bar: {
baz: function() {
alert('Eureka!');
}
}
};
//foo.bar.baz();
var callme = "foo.bar.baz";
var fn = window[callme.split(".")[0]];//get the first prop. bar
var len = callme.split(".").length;//length of obj tree
for(i=1;i < len;i++)
{//search for the next obj
fn = fn[callme.split(".")[i]];
}
if(typeof(fn) == "function")
{//check and call
fn();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With