JavaScript - 继承B.prototype = new A()的数组

San*_*an4 5 javascript oop inheritance prototypal-inheritance

(我是JavaScript的新手).以下代码:

function A() {
    console.log('Constructing A');
    this.a = new Array();
}
function B(x) {
    console.log('Constructing B');
    this.a.push(x);
    this.b = x;
}
B.prototype = new A();
b1 = new B(10);
b2 = new B(11);
console.log('b1', b1);
console.log('b2', b2);?
Run Code Online (Sandbox Code Playgroud)

b1和b2中的结果共享单个 this .a数组(但不同 this.b).这就像一张浅色的副本.

我不太明白什么是创建单独 this.a数组的正确方法.我希望它们继承,因为这是代码的逻辑,除了我不想在每个子对象中创建它们(在我的情况下有很多子对象).

Sam*_*son 3

我对这个问题的解释很感兴趣。我读过 @Niko 的重复问题,但似乎这就是造成差异的原因:

 function A() {
        console.log('Constructing A');
        this.a=new Array();
    }

    function B(x) {
        console.log('Constructing B');
        A.call(this); //--> calling the super() constructor creates a new array
        this.a.push(x);
    }

    B.prototype = new A();

    b1 = new B(11);
    b2 = new B(12);
    console.log(b1.a);
    console.log(b2.a);
Run Code Online (Sandbox Code Playgroud)