JavaScript: inheritance
-
14-11-2019 - |
Question
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]}
Solution
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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow