Created
May 4, 2012 13:12
-
-
Save padolsey/2594728 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
// Object traversal method detection: | |
methodIsDefined('alert', window); // true | |
methodIsDefined('window.alert', window); // true | |
methodIsDefined('alert.apply', window); // true | |
methodIsDefined('alert', {}); // false | |
methodIsDefined('foo', window); // false | |
methodIsDefined('window.foo', window); // false | |
methodIsDefined('foo.bar.doesNotExist', {}); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ops, pressed the send button too early...
Every time I need to use a method like that I wish JavaScript had support for something like
lorem['ipsum.dolor.amet'] = 123
it would simplify logic in so many cases. - It would create the nested objects automatically if they doesn't exist and if you are getting the value and it doesn't exist just returnundefined
instead of throwing an error. Would help even more in cases where you need to pass a dynamic property name.