A Function To Print Prototype Chain For A Given Object
Sometimes I get lost in prototype chain of my JavaScript objects, so I would like to have a function that would print in a friendly way the prototype chain of a given object. I am
Solution 1:
This function shows prototype chain of any object clearly:
functiontracePrototypeChainOf(object) {
var proto = object.constructor.prototype;
var result = '';
while (proto) {
result += ' -> ' + proto.constructor.name;
proto = Object.getPrototypeOf(proto)
}
return result;
}
var trace = tracePrototypeChainOf(document.body)
alert(trace);
tracePrototypeChainOf(document.body)
returns "-> HTMLBodyElement -> HTMLElement -> Element -> Node -> EventTarget -> Object"
Solution 2:
You could use something like the following:
functionprintPrototype(obj, i) {
var n = Number(i || 0);
var indent = Array(2 + n).join("-");
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
console.log(indent, key, ": ", obj[key]);
}
}
if(obj) {
if(Object.getPrototypeOf) {
printPrototype(Object.getPrototypeOf(obj), n + 1);
} elseif(obj.__proto__) {
printPrototype(obj.__proto__, n + 1);
}
}
}
http://jsfiddle.net/5fv1tv1x/1/
Call it like so:
printPrototype(myObj);
It may require some modification to fit your exact needs. In node, you may also need some extra guards ( I tested in Chrome so I only needed to guard against 'obj' being undefined before recursing).
Solution 3:
functionprotoChain(o) {
var chain = [];
(functionprotoChainImpl(o) {
if (o == null) {
return;
}
var proto = Object.getPrototypeOf(o);
if (proto) {
chain.push(proto.hasOwnProperty('constructor') ? proto.constructor.name : 'undefined');
returnprotoChainImpl(proto);
}
})(o);
return chain;
}
classExampleParent {}
classExampleextendsExampleParent {}
document.write(
'function(){}: ', protoChain(function() {}),
'<br>',
'[]: ', protoChain([]),
'<br>',
'Example: ', protoChain(newExample()),
);
Post a Comment for "A Function To Print Prototype Chain For A Given Object"