IntermediateLesson 11 of 16
Classes & Object-Oriented Programming – JavaScript
class, extends, private fields, getters and prototypes.
Since ES2015 there is the class syntax. constructor initializes the object, this is the current object, extends inherits and super calls the parent class.
class Tier {
constructor(name) {
this.name = name;
}
sprich() {
return this.name + " makes a sound";
}
}
class Hund extends Tier {
sprich() {
return this.name + " says Woof!";
}
}
for (const t of [new Tier("Something"), new Hund("Rex")]) {
console.log(t.sprich());
}Private fields start with # and are truly inaccessible from outside. Getters/setters and static belong here as well:
class Konto {
#saldo = 0;
static anzahl = 0;
constructor(inhaber) {
this.inhaber = inhaber;
Konto.anzahl++;
}
einzahlen(betrag) {
if (betrag <= 0) throw new RangeError("Amount must be positive");
this.#saldo += betrag;
return this; // enables chaining
}
get saldo() {
return this.#saldo;
}
}
const k = new Konto("Ada").einzahlen(50).einzahlen(25);
console.log(k.saldo, Konto.anzahl); // 75 1Under the hood, classes are syntax for prototypes: every object has a prototype in which missing properties are looked up (the prototype chain).
console.log(typeof Tier); // function
console.log(Object.getPrototypeOf(Hund.prototype) === Tier.prototype); // true
const rex = new Hund("Rex");
console.log(rex instanceof Hund, rex instanceof Tier, rex.hasOwnProperty("sprich")); // true true falseTipPrefer composition over deep inheritance: small functions and objects that you combine are often more flexible in JavaScript than class hierarchies.