How does __proto__ differ from constructor.prototy

2018-12-31 21:24发布

function Gadget(name, color)
{
   this.name = name;
   this.color = color;
}

Gadget.prototype.rating = 3

var newtoy = new Gadget("webcam", "black")

newtoy.constructor.prototype.constructor.prototype.constructor.prototype 

It always returns the object with rating = 3.

But if I do the following:

newtoy.__proto__.__proto__.__proto__

The chain ends up returning null.

Also in Internet Explorer how would I check the null if there is not a __proto__ property?

7条回答
孤独寂梦人
2楼-- · 2018-12-31 21:52

I've been trying to wrap my head around this recently and finally came up with this "map" that I think sheds full light over the matter

http://i.stack.imgur.com/KFzI3.png enter image description here

I know I'm not the first one making this up but it was more interesting figuring it out that finding it :-). Anyway, after that I found e.g. this another diagram that I think says basicly the same:

Javascript object layout

The most surprising thing for me was discovering that Object.__proto__ points to Function.prototype, instead of Object.prototype, but I'm sure there's a good reason for that :-)

I paste the code mentioned in the image here as well for if anyone wants to test it. Note that some properties are added to the objects for making easy to know where we are after some jumps:

Object.O1='';
Object.prototype.Op1='';

Function.F1 = '';
Function.prototype.Fp1 = '';

Cat = function(){};
Cat.C1 = '';
Cat.prototype.Cp1 = '';

mycat = new Cat();
o = {};

// EDITED: using console.dir now instead of console.log
console.dir(mycat);
console.dir(o);
查看更多
登录 后发表回答