function Entity() {
this.a = {a: 4};
this.b = 5;
}
function Thing() {}
Thing.prototype = new Entity;
var thing1 = new Thing;
thing1.a.a = 3;
thing1.b = 4;
var thing2 = new Thing;
console.log(thing2.a.a); // prints 3 instead of 4. I would like 4.
console.log(thing2.b) // prints 5 as wanted
我在 javascript 中设置原型继承时遇到了困难。理想情况下,我希望 thing1 和 thing2 都有自己的“新实体原型”的干净副本。
usingthis.__proto__
是我想避免的事情
[编辑]
我对它的工作原理有一个粗略的了解。
设置 thing1.b 会设置 Thing 实例的 b 属性。它不会触及原型链中定义的 Entity.b。
无法在 Thing 实例上设置 thing1.aa,因为它会引发“无法在未定义时设置”错误。那时它会沿着原型链查找 Entity.a,它已定义并将 Entity.aa 设置为新值。
[进一步编辑]
正如@IvoWetzel 所说,设置 thing1.b 不会触及原型链,因为设置属性不会。设置 thing1.aa 有两个步骤。thing1.a 上的getter,它触及原型链,后跟 .a 的 setter