Created
May 4, 2012 13:12
-
-
Save padolsey/2594728 to your computer and use it in GitHub Desktop.
This file contains 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 |
I have something similar on amd-utils/object/has, but it doesn't really check for a method, just the existence of a property. The real "magic" is on the object/get module, very similar implementation.
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 return undefined
instead of throwing an error. Would help even more in cases where you need to pass a dynamic property name.
@millermedeiros it does! Just not the way that you want :P
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote some similar code to this a while back, for the jQuery getObject plugin, but have since adapted it a bit for grunt:
https://github.com/cowboy/grunt/blob/master/lib/util/namespace.js
https://github.com/cowboy/grunt/blob/master/test/util/namespace_test.js
If you have any improvements, let me know!