简体   繁体   English

写入__proto__对象

[英]Writing to __proto__ object

Say I have an object like so: 说我有一个这样的对象:

const obj1 = {foo:'bar'};

and then I create a "copy", ( obj1 is now the proto of obj2 ): 然后创建一个“副本”,( obj1现在是obj2原型 ):

const obj2 = Object.create(obj1);

if I call 如果我打电话

obj2.foo = 3;

or 要么

obj2.x = {};

my question is - will obj1 ever get written to, or will it never be written to? 我的问题是obj1会被写入,还是永远不会被写入? As far as I know, only the top level object will get written to - the prototype object is never modified. 据我所知,只有顶层对象会被写入-原型对象永远不会被修改。

In other words, are there any circumstances where is I set properties obj2, obj1 will get modified? 换句话说,在任何情况下我都应该设置属性obj2,而obj1会被修改吗?

obj1 can be written if it's accessed directly like Object.getPrototypeOf(obj2).foo = 3 but it's unlikely that this can be done not on purpose. 如果直接像访问Object.getPrototypeOf(obj2).foo = 3那样访问obj1可以将其编写,但是不太可能故意这样做。

It's possible to write to obj1 not on purpose if it was designed without inheritance in mind, eg: 如果在设计时没有刻意继承,则有可能obj1地写入obj1 ,例如:

const obj1 = {
  get foo() { return obj1._foo },
  set foo(v) { obj1._foo = v}
}

const obj2 = Object.create(obj1);
obj2.foo = 3;

Referring an object directly instead of this inside object methods was a common way to maintain proper context in legacy ES3/ES5 code. 参照对象,而不是直接的this内部对象的方法是保持在遗留ES3 / ES5代码适当的上下文的常用方法。

Are there any circumstances where is I set properties obj2 , obj1 will get modified? 在任何情况下我都可以将属性obj2设置为obj1吗?

Only when obj1 has defined a setter property that is inherited by obj2 (and what exactly happens then depends on the implementation of the setter). 仅当obj1定义了由obj2继承的setter属性(然后实际发生什么取决于setter的实现)时。 Otherwise, a property assignment on obj2 will always create/change properties on obj2 itself. 否则,对obj2的属性分配将始终在obj2本身上创建/更改属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM