How to determine if a JavaScript function is defined?
javascript
Solution
The code:
window[functions [i]]
Is checking for `window['ff.showAlert']` but what you really want to check for is:
window['ff']['showAlert']
or
window.ff.showAlert
For this, you need to traverse the namespace (`window`->`ff`->...):
function methodIsDefined(fn, obj) {
var ns = fn.split('.');
fn = ns.pop();
do {
if (!ns[0]) {
return typeof obj[fn] === 'function';
}
} while(obj = obj[ns.shift()]);
return false;
}
E.g.
methodIsDefined('ff.showAlert', window); // => true
methodIsDefined('ff.foo', window); // => false
Problem
I want to check if a function is defined (I don't care how, I mean it is callable) sample code: ``` var functions = { 'alert':'alert', 'undefinedFunction':'undefinedFunction', 'ff.showAlert':'ff.showAlert' }; var ff = { showAlert: function() { alert('the function works'); } }; for (i in functions) { console.log(i+' : '+typeof window[functions [i]]); } ``` this returns: ``` alert : function undefinedFunction : undefined ff.showAlert : undefined console.log(typeof window.ff.showAlert); return function ``` Live demo Is there a way to programmatically check if a function exists?