Skip to content

Instantly share code, notes, and snippets.

@padolsey
Created May 4, 2012 13:12
Show Gist options
  • Save padolsey/2594728 to your computer and use it in GitHub Desktop.
Save padolsey/2594728 to your computer and use it in GitHub Desktop.
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
@cowboy
Copy link

cowboy commented May 4, 2012

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!

@millermedeiros
Copy link

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.

@millermedeiros
Copy link

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.

@cowboy
Copy link

cowboy commented May 4, 2012

@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