Skip to content

Instantly share code, notes, and snippets.

@osartun
Created May 15, 2013 11:19
Show Gist options
  • Save osartun/5583290 to your computer and use it in GitHub Desktop.
Save osartun/5583290 to your computer and use it in GitHub Desktop.
Defines a global getPrototoypeChain function that returns an array of all the objects which are part of the passed object's prototype chain.
var getPrototype = typeof Object.getPrototypeOf === "function" ?
Object.getPrototypeOf :
typeof "".__proto__ === "object" ?
function (obj) {
return obj ? obj.__proto__ : null;
} :
function (obj) {
return obj && obj.constructor ? obj.constructor.prototype : null;
},
nativeIndexOf = Array.prototype.indexOf,
indexOf = typeof _ === "object" && typeof _.indexOf === "function" ? _.indexOf : function (arr, item) {
if (arr == null) return -1;
var i = 0, l = arr.length;
if (nativeIndexOf && arr.indexOf === nativeIndexOf) return arr.indexOf(item);
for (; i < l; i++) if (arr[i] === item) return i;
return -1;
};
getPrototypeChain = function (obj) { // defines it globally
var list = [obj];
while ( obj && (obj = getPrototype(obj)) && obj !== list[list.length - 1] ) {
if (indexOf(list, obj) === -1) { // Keep it unique
list.push(obj);
}
}
return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment