Cao,
U funkciji Child je potrebno da pozoves funkciju Parent sto vec i radis. Medjutim moras da prosledis drugi kontekst toj funkciji. Kontekst objekta Child. U parent funkciji niz definisi sa this.collection umesto var collection.
Evo ispravljenog koda.
Code:
function Parent() {
this.collection = [];
this.add = function (i) {
this.collection.push(i);
}
this.getCount = function () { return this.collection.length }
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var x1 = new Child();
x1.add(1);
var x1Count = x1.getCount();
var x2 = new Child();
x2.add(2);
x2.add(3);
var x1Count = x1.getCount();
var x2Count = x2.getCount();
console.log(x1Count);
console.log(x2Count);
console.log(x1["collection"]);
console.log(x2["collection"]);
Jos jedna bitna stvar. Sve funkcije Parent objekta stavi na prototip kako ne bi imao nove instance funkcija za svaki novokreirani Child objekat. Ovako:
Code:
function Parent() {
this.collection = [];
}
Parent.prototype.add = function (i) {
this.collection.push(i);
}
Parent.prototype.getCount = function () {
return this.collection.length;
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var x1 = new Child();
x1.add(1);
var x1Count = x1.getCount();
var x2 = new Child();
x2.add(2);
x2.add(3);
var x1Count = x1.getCount();
var x2Count = x2.getCount();
console.log(x1Count);
console.log(x2Count);
console.log(x1["collection"]);
console.log(x2["collection"]);