为什么可以检索原型但在JavaScript中未定义__proto__? [英] Why the prototype can be retrieved but the __proto__ is undefined in JavaScript?

查看:159
本文介绍了为什么可以检索原型但在JavaScript中未定义__proto__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在学习JavaScript prototype__proto__,并找到几个有用的链接

__proto__VS. JavaScript原型

__proto__与Constructor.prototype有何不同?

我可以在Chrome下的以下代码中获取对象f__proto__值.

var Foo = function() {}
var f = new Foo();
f.__proto__
> Foo {} 

但是,将Foo.prototype.__proto__设置为null后,__proto__的值是undefined.

var Foo = function() {}
Foo.prototype = {name: 'cat', age: 10};
Foo.prototype.__proto__ = null;
var f = new Foo();
f.__proto__
> undefined 

但是我可以得到f.name的值,即cat.这是我的理解,因为值f.name是可检索的,所以对象f__proto__应该指向Foo.prototype.为什么f.__proto__的值是undefined?

解决方案

obj.__proto__未定义如果原型链不包含Object.prototype :

这按指定方式工作. ES6 __proto__是在Object.prototype上定义的吸气剂.对于在其原型链中没有该对象的对象,它是不可访问的(就像没有hasOwnProperty一样).您需要改用Object.getPrototypeOf.

Now I am learning JavaScript prototype and __proto__, and find several useful links

__proto__ VS. prototype in JavaScript

How does __proto__ differ from constructor.prototype?

I can get the value of __proto__ of object f in the following codes under Chrome.

var Foo = function() {}
var f = new Foo();
f.__proto__
> Foo {} 

However, after setting the Foo.prototype.__proto__ to null, the value of __proto__ is undefined.

var Foo = function() {}
Foo.prototype = {name: 'cat', age: 10};
Foo.prototype.__proto__ = null;
var f = new Foo();
f.__proto__
> undefined 

But I can get the value of f.name, which is cat. Here is my understanding, since the value f.name can be retrievable, the __proto__ of object f should point to Foo.prototype. Why the value of f.__proto__ is undefined?

解决方案

According to the ES2015 spec, __proto__ is an accessor property that is inherited from Object.prototype.

Since your prototype chain for the instance f is rooted in null, rather than Object.prototype, the f object does not inherit any properties from Object.prototype, including Object.prototype.__proto__.

The object still knows its prototype internally (through [[Prototype]] internal slot), but it does not inherit the __proto__ accessor property for getting this value. You can still access it through Object.getPrototypeOf(f), though.

See also the resolution on the Chromium issue "obj.__proto__ is undefined if prototype chain does not contain Object.prototype":

This is working as specified. ES6 __proto__ is a getter defined on Object.prototype. For an object that doesn't have that in its prototype chain it is not accessible (just like, say, hasOwnProperty isn't). You need to use Object.getPrototypeOf instead.

这篇关于为什么可以检索原型但在JavaScript中未定义__proto__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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