我如何使用链式javascript原型继承?

Ray*_*nos 3 javascript prototyping scope prototype this

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
Run Code Online (Sandbox Code Playgroud)

我在javascript中设置原型继承时遇到了困难.理想情况下,我希望thing1和thing2都拥有自己的"新实体原型"的干净副本.

使用this.__proto__是我想避免的

[编辑]

我对这是如何工作有一个大概的了解.

设置thing1.b在Thing实例上设置b属性.它不接触原型链中定义的Entity.b.

在Thing实例上设置thing1.aa的地方无法完成,因为它会抛出"无法设置未定义"错误.那是当它上升到原型链以找到定义的Entity.a并将Entity.aa设置为新值.

[进一步编辑]

正如@IvoWetzel所说设置thing1.b不会触及原型链,因为设置属性不会.设置thing1.aa的地方有两个步骤.在thing1.a上的一个getter,触及原型链,后跟一个.a的setter

CMS*_*CMS 6

你可以做的是Entity构造函数的逻辑应用于内部Thing,例如:

function Entity() {
    this.a = {a: 4};
    this.b = 5;
}
Entity.prototype.c = 6;

function Thing() {
  Entity.apply(this, arguments); // ejecutes the assignments made in Entity
}
Thing.prototype = new Entity;

var a = new Thing;
a.a.a = 3;

var b = new Thing;
console.log(a.a.a); // 3
console.log(b.a.a); // 4

console.log(a.b);   // 5
console.log(b.b);   // 5

console.log(a.c);   // 6
console.log(b.c);   // 6
Run Code Online (Sandbox Code Playgroud)