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

时间:2012-08-26 10:59:18

标签: 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);​

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

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

在您的代码中:

> 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();

这将B的原型设置为A的实例。因此,B的所有实例将在其[[Prototype]]链上具有该A的实例。

在B构造函数中,this引用了一个继承自B.prototype的新对象,因此this.a将引用a的{​​{1}}属性。

B.prototype

所以现在> b1 = new B(10); B.prototype.a

[10]

现在> b2 = new B(11); B.prototype.a