Skip to content

Instantly share code, notes, and snippets.

@h2non
Last active December 16, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2non/5354415 to your computer and use it in GitHub Desktop.
Save h2non/5354415 to your computer and use it in GitHub Desktop.
Implement a recursive reflection in JavaScript prototype chain inheritance
// for ES5 compliant engines (tested in Chrome, FF and IE9+)
// Under WTFPL license ;)
function getObjectInheritance(obj) {
var hierarchy = [];
if (['boolean', 'number', 'string', 'undefined'].indexOf(typeof obj) !== -1 || obj === null) { // support for 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
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;
}
// test
getObjectInheritance(HTMLDivElement).join(' -> ');
// "Object -> Node -> Element -> HTMLElement -> HTMLDivElement"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment