使用Object.create(null)创建对象时__proto__如何工作 [英] How does __proto__ work when object is created with Object.create(null)
问题描述
考虑以下javascript代码
Consider the following javascript code
var a = Object.create(null);
a.foo = 1;
var b = Object.create(a);
console.log(b.foo); //prints 1
console.log(b.__proto__); //prints undefined
b.__proto__ = null;
console.log(b.__proto__); //prints null
console.log(b.foo); //prints 1
有人能解释即使将 b .__ proto __
设置为null之后,对象 b
如何访问 a
的"foo"属性吗?用于访问 a
的属性的内部链接是什么?
Can anyone explain how object b
is accessing the "foo" property of a
even after setting b.__proto__
to null? What is the internal link which is used to access the property of a
?
我尝试在SO中搜索可能的解释,但找不到关于Java特定行为的任何解释.
I tried searching through SO for possible explanations but couldn't find any explanation for this particular behaviour of Javascript.
推荐答案
您的问题是您正在使用已弃用 __ proto __
属性,它是 Object.prototype
上的吸气剂/设置器-但是您的对象不会继承该对象,因此首先是 undefined
,赋值会创建一个标准属性名称为 __ proto __
.
Your problem is that you are using the deprecated __proto__
property, which is a getter/setter on Object.prototype
- but your objects don't inherit from that, so it's undefined
at first and the assignment creates a standard property with the name __proto__
.
使用正确的 Object.getPrototypeOf
/>代替code> Object.setPrototypeOf ,代码将完成您期望的操作:
Use the proper Object.getPrototypeOf
/Object.setPrototypeOf
instead and the code will do what you expect:
var a = Object.create(null);
a.foo = 1;
var b = Object.create(a);
console.log(b.foo); // 1
console.log(Object.getPrototypeOf(b)); // {foo:1} - a
Object.setPrototypeOf(b, null);
console.log(Object.getPrototypeOf(b)); // null
console.log(b.foo); // undefined
这篇关于使用Object.create(null)创建对象时__proto__如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!