DraganS
DraganS

Reputation: 2709

JavaScript: inheritance

I tried to make inheritance, but I didn't expect that this.array will act like static member. How can I make it 'protected/public':

function A() {
    this.array = [];
}

function B() {
    this.array.push(1);
}
B.prototype.constructor=B;
B.prototype = new A();

Firebug:

>>> b = new B();
A { array=[1]}
>>> b = new B();
A { array=[2]}
>>> b = new B()
A { array=[3]}

Upvotes: 0

Views: 93

Answers (1)

user1170510
user1170510

Reputation:

Not "private/protected", but this will make a new Array for each B.

function A() {
    this.array = [];
}

function B() {
    A.apply(this); // apply the A constructor to the new object
    this.array.push(1);
}
// B.prototype.constructor=B; // pointless
B.prototype = new A();

Upvotes: 2

Related Questions