JavaScriptFundamental (ES6), part 1
Multi-level class inheritance in JavaScript
134 inheritance with super, and a static factory that knows its subclass
hardBuild three levels — Vehicle, Danfo, Keke — where each fare calls super.fare and adds to it. Give Danfo a static factory that parses a plate string and returns new this(...), so calling it on Keke builds a Keke. Then show what happens if you touch this before super().
Stuck? Three hints, smallest first
- 1.
super.fare(km)in a method looks up the prototype chain from where the method was defined, not from the instance. - 2. In a static method,
thisis the class it was called on.new this(...)is what makes the factory inherit properly;new Danfo(...)would not. - 3. A derived constructor has no
thisuntilsuper()has run. Reading or writing it before then is aReferenceError, not undefined.
class Vehicle {
static #built = 0;
#plate;
constructor(plate, seats) {
this.#plate = plate;
this.seats = seats;
Vehicle.#built += 1;
}
static get built() { return Vehicle.#built; }
get plate() { return this.#plate; }
fare(km) { return 100 * km; }
describe() { return `${this.constructor.name} ${this.#plate}`; }
}
class Danfo extends Vehicle {
constructor(plate, seats, conductor) {
super(plate, seats);
this.conductor = conductor;
}
fare(km) { return super.fare(km) + 50 * this.seats; }
static fromPlate(text) {
const [plate, seats = '14'] = text.split('/');
return new this(plate, Number(seats), 'unknown');
}
}
class Keke extends Danfo {
fare(km) { return super.fare(km) / 2; }
}
class Broken extends Vehicle {
constructor(plate) {
this.tooEarly = true;
super(plate, 1);
}
}
const builtBefore = Vehicle.built;
const bus = new Danfo('LSD-234-AB', 14, 'Sunday');
const keke = new Keke('KEK-11-XY', 3, 'none');
const parsed = Danfo.fromPlate('EPE-901-CD/18');
const parsedKeke = Keke.fromPlate('IKD-77-EF/3');
const defaulted = Danfo.fromPlate('ABC-123-ZZ');
const builtHere = Vehicle.built - builtBefore;
let beforeSuper = 'no error';
try { new Broken('XX-000'); } catch (e) { beforeSuper = e.constructor.name; }
console.log('fares :', bus.fare(10), keke.fare(10));
console.log('factory:', parsed.constructor.name, parsedKeke.constructor.name, defaulted.seats);
console.log('built :', builtHere, '| this before super:', beforeSuper);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('each override adds to the one above it', [bus.fare(10), keke.fare(10)], [1700, 575]);
test('so Keke reaches Vehicle through Danfo, two links up', keke.fare(10) * 2 - 50 * keke.seats, 1000);
test('a static factory built with new this returns the class it was called on', [parsed.constructor.name, parsedKeke.constructor.name], ['Danfo', 'Keke']);
test('the instance is complete, and a plate with no seat count takes the default', [parsedKeke instanceof Keke, parsedKeke.conductor, defaulted.seats], [true, 'unknown', 14]);
test('instanceof holds at every level of the chain', [keke instanceof Keke, keke instanceof Danfo, keke instanceof Vehicle], [true, true, true]);
test('a base-class method reads the private field and the runtime name', keke.describe(), 'Keke KEK-11-XY');
test('five constructions, all counted by the base class', builtHere, 5);
test('touching this before super is a ReferenceError, so nothing was counted', beforeSuper, 'ReferenceError');
test('and the private field never appears as an own property', Object.keys(bus), ['seats', 'conductor']);
super.method() is not "call the parent of this object" — it looks up from the prototype where the method was written. That is why Keke.fare reaching super.fare lands in Danfo, whose own super.fare lands in Vehicle, and each level adds its part on the way back. Write the chain wrong once and you get a silently plausible number, which is why the fare assertions spell out the arithmetic.
new this(...) inside a static method is the detail that makes a factory inheritable. In a static method this is the class the call was made on, so Keke.fromPlate constructs a Keke with no extra code; hard-coding new Danfo(...) would quietly downgrade every subclass. The same reasoning is why Array.prototype.map and friends were given a species hook.
The ReferenceError is the rule people meet by accident. In a derived constructor, this does not exist until super() returns — the parent creates it. So super() goes first, always, and any argument massaging you need before it must be done with local variables or parameters. Note too that the private #plate is reachable from Vehicle's own method on a Keke instance, but never from outside and never in Object.keys.