JavaScript: ereditarietà
-
14-11-2019 - |
Domanda
Ho provato a fare l'ereditarietà, ma non mi aspettavo che this.array
fungerà come un membro statico.Come posso renderlo 'protetto / pubblico':
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]}
. Soluzione
Non "privato / protetto", ma questo farà un nuovo array per ogni 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();
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow