ECMAScript 5 Inheritance
Rekapitulation: Vererbung in JavaScript dreht sich um die Klonen von Eigenschaften eines
bestehenden Objektes und dem dynamischen Erweitern des neuen Objekts. Das Ausgangsobjekt
nennt man den "Prototypen" (aber nicht verwechseln mit der prototyp
-Property
einer Funktion. Ein solcher Prototyp ist nichts anderes als ein simples Objekt, das
seine Eigenschaften teilt (mit dem Klon) - als "Parent".
Hierbei wird zunächst nichts kopiert, sondern JavaScript delegiert!
Bisher:
BaseClass.count = 0;
BaseClass.prototype = {
id: 0,
name: '',
toString: function() { return 'Base-Object ' + this.id }
}
function BaseClass () {
this.id = ++BaseClass.count;
console.log("BaseClass constructor")
}
SubClass.prototype = new BaseClass();
SubClass.prototype.toString = function() { return 'Sub-Object ' + this.id }
function SubClass () {
BaseClass.call(this);
console.log("SubClass constructor");
}
Neu:
BasisKlasse.count = 0;
BasisKlasse.prototype = {
id: 0,
name: '',
toString: function() { return 'Basis-Objekt ' + this.id }
}
function BasisKlasse () {
this.id = ++BasisKlasse.count;
console.log("BasisKlasse Konstruktor")
}
KindKlasse.prototype = Object.create(BasisKlasse.prototype);
KindKlasse.prototype.toString = function() { return 'Kind-Objekt ' + this.id }
function KindKlasse () {
BasisKlasse.call(this);
console.log("SubClass Konstruktor");
}
Mehrfachvererbung
JavaScript definiert keine direkten Weg, aber natürlich lässt sich ein solches Verhalten "bauen". Ein Beispiel sind die Mixins (sieh hier Generell gilt: über kurz oder lang schreiben Sie sich eine eigene OO-Library.
Zweites Argument bei Object.create(): properties
Konto.count = 0;
function Konto () {
this.id = ++Konto.count;
this.stand = 0;
}
Konto.prototype = Object.create(null,{
einzahlen: { value: function(betrag) { console.log(this.id); this.stand += betrag; } },
auszahlen: { value: function(betrag) { if(betrag > this.stand) return false; this.stand -= betrag; return true; }}
});
GiroKonto.prototype = Object.create(Konto.prototype, {
auszahlen: { value: function(betrag) { if(betrag > this.stand + this.dispo) return false; this.stand -= betrag; return true; }}
});
function GiroKonto() {
Konto.call(this);
this.dispo = 0;
}
var konto1 = new Konto();
var giro1 = new GiroKonto();