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');
}