How can I see the prototype chain of a Javascript object?

Given the following code:

function a() {} function b() {} b.prototype = new a(); var b1 = new b(); 

We can stay that a was added to the b prototype chain. Fine. And that's right:

 b1 instanceof b b1 instanceof a b1 instanceof Object 

My question is: what if we do not know the origin of b1 in advance? How can we find members of our prototype chain? Ideally, I need an array like [b, a, Object] or ["b", "a", "Object"] .

Is it possible? In my opinion, I saw an answer somewhere on SO that described how to find out, but I can't let life find me again.

+17
javascript prototype prototypal-inheritance
Feb 11 2018-10-11T00
source share
3 answers

Well, the prototype of the communication between objects ( [[Prototype]] ) is internal, some implementations, such as Mozilla, display it as obj.__proto__ .

Object.getPrototypeOf method of ECMAScript 5th Edition is what you need, but it is not implemented right now on most JavaScript engines.

Look at this John Resig implementation , it has a trap, it relies on the constructor property for engines, t __proto__ :

 if ( typeof Object.getPrototypeOf !== "function" ) { if ( typeof "test".__proto__ === "object" ) { Object.getPrototypeOf = function(object){ return object.__proto__; }; } else { Object.getPrototypeOf = function(object){ // May break if the constructor has been tampered with return object.constructor.prototype; }; } } 

Remember that this is not 100% more reliable, as the constructor property is changed on any object.

+7
Feb 11 2018-10-11T00
source share

You can use the constructor property of an object to find the prototype there, and then scroll through it until you reach the end of the rainbow.

 function getPrototypes(o) { return (function gp(o, protos) { var c = o.constructor; if (c.prototype) { protos.push(c.prototype); return gp(c.prototype, protos); } return protos; })(o, []); } 

(maybe) (or maybe not :-) give me a second) (well shit, I think it's possible, but ignore this code)

[edit] wow, this blows my head completely - this function closes, but not quite right; prototyping is weird, and I feel scared and lonely. I suggest paying attention only to the amazing @CMS above.

+2
Feb 11 2018-10-11T00
source share

Here is the starting point:

 Object.prototype.getConstructorNames=function(){ return Object.keys(window).filter(function(e){ return typeof window[e]==="function" && this instanceof window[e]},this) } 

Of course, this is really incomplete, but I think that it will work in most cases, and if someone wants to add to it, he can.

0
May 18 '15 at 15:21
source share



All Articles