__proto__ 与 constructor.prototype 有何不同? [英] How does __proto__ differ from constructor.prototype?

查看:35
本文介绍了__proto__ 与 constructor.prototype 有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function Gadget(name, color){this.name = 名称;this.color = 颜色;}Gadget.prototype.rating = 3var newtoy = new Gadget("网络摄像头", "黑色")newtoy.constructor.prototype.constructor.prototype.constructor.prototype

它总是返回 rating = 3 的对象.

但是如果我执行以下操作:

newtoy.__proto__.__proto__.__proto__

链最终返回null.

同样在 Internet Explorer 中,如果没有 __proto__ 属性,我将如何检查空值?

解决方案

我最近一直在努力解决这个问题,终于想出了这张地图",我认为它可以充分说明这个问题

最令我惊讶的是发现 Object.__proto__ 指向 Function.prototype,而不是 Object.prototype,但我肯定有一个很好的理由:-)

如果有人想测试它,我也将图片中提到的代码粘贴到此处.请注意,一些属性被添加到对象中,以便在一些跳转后更容易知道我们的位置:

Object.O1='';Object.prototype.Op1='';函数.F1 = '';Function.prototype.Fp1 = '';猫 = 函数(){};Cat.C1 = '';Cat.prototype.Cp1 = '';mycat = new Cat();o = {};//现在使用 console.dir 而不是 console.log控制台目录(mycat);控制台.dir(o);

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?

解决方案

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

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);

这篇关于__proto__ 与 constructor.prototype 有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆