Skip to content

Instantly share code, notes, and snippets.

@h2non
Created February 6, 2015 18:55
Show Gist options
  • Save h2non/6dd79c4312d0b20ccc4a to your computer and use it in GitHub Desktop.
Save h2non/6dd79c4312d0b20ccc4a to your computer and use it in GitHub Desktop.
Recursively inspect the prototype chain inheritance of a given object in JavaScript (inspired in Ruby's Class.ancestors)
// Under WTFPL license ;)
function ancestors(obj) {
var hierarchy = [];
if (['boolean', 'number', 'string', 'undefined'].indexOf(typeof obj) !== -1 || obj === null) { // primitives types
obj = Object(obj);
} else if (typeof obj === 'function') {
hierarchy.push(
obj.name ||
(obj.toString().match(/function (\w*)/) ||
obj.toString().match(/\[object (\w*)\]/))[1] ||
'Anonymous Function'
);
obj = obj.prototype;
} else if (obj.toString() !== '[object Object]' && obj.prototype) { // fix Objects instances and IE issue
hierarchy.push(
obj.prototype.constructor.name ||
(obj.prototype.constructor.toString().match(/function (\w*)/) ||
obj.prototype.constructor.toString().match(/\[object (\w*)\]/))[1] ||
'Anonymous Function'
);
obj = obj.prototype;
} else if (!Object.getPrototypeOf(obj) && obj.constructor) {
hierarchy.push(
obj.constructor.name ||
(obj.constructor.toString().match(/function (\w*)/) ||
obj.constructor.toString().match(/\[object (\w*)\]/))[1] ||
'Anonymous Function'
)
}
while (obj = Object.getPrototypeOf(obj)) {
if (obj && obj.constructor) {
hierarchy.push(
obj.constructor.name ||
(obj.constructor.toString().match(/function (\w*)/) ||
obj.constructor.toString().match(/\[object (\w*)\]/))[1] ||
'Anonymous Function'
)
}
}
return hierarchy
}
@h2non
Copy link
Author

h2non commented Feb 6, 2015

Test it:

ancestors(HTMLElement)
// -> ["HTMLElement", "Element", "Node", "EventTarget", "Object"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment