JavaScript - inheriting arrays with B.prototype = new A ()

(I'm new to JavaScript). The following code:

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

Results in b1 and b2 sharing the same this.a array (but different this.b). It is like a shallow copy.

I do not quite understand how to create separate arrays correctly this.a. I want them to be inherited, because this is the logic of the code, but I do not want to create them in every child (and in my case a lot of children).

+5
source share
2 answers

I am very interested in an explanation of this problem. I read the @ Niko duplicate question, but this seems to be what makes the difference:

 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);
+3
source

In your code:

> 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 A [[Prototype]].

B this , B.prototype, this.a a B.prototype.

> b1 = new B(10);

, B.prototype.a [10].

> b2 = new B(11);

B.prototype.a [10, 11].

0

All Articles