Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

extends and super in JavaScript classes

45 extends, super and an overridden method

fair

Extend a vehicle class, call super() in the child constructor, and override a method so that it wraps the parent's version with super.describe() rather than replacing it. Then find out what happens if the child constructor touches this before calling super().

Stuck? Three hints, smallest first
  1. 1. A derived constructor must call super() before it may read or write this.
  2. 2. super.method() calls the parent version with the same this. Calling this.method() instead would recurse for ever.
  3. 3. A subclass inherits statics as well, because the class object itself has the parent class as its prototype.

The answer

class Vehicle {
  static fleet = 'Lagos';
  constructor(plate) {
    this.plate = plate;
    this.trips = 0;
  }
  describe() {
    return `vehicle ${this.plate}`;
  }
  run(km) {
    this.trips++;
    return km;
  }
}

class Danfo extends Vehicle {
  constructor(plate, seats) {
    super(plate);                             // parent first
    this.seats = seats;
  }
  describe() {
    return `danfo ${super.describe()} with ${this.seats} seats`;
  }
  run(km) {
    return super.run(km) * this.seats;        // parent counts, child scales
  }
}

const bus = new Danfo('LSD-244-XA', 14);
const scaled = bus.run(10);

const tooEarly = (() => {
  class Broken extends Vehicle {
    constructor() {
      this.plate = 'set before super';        // illegal
      super('never reached');
    }
  }
  try { new Broken(); return 'built'; } catch (e) { return e.constructor.name; }
})();

console.log('keys     :', Object.keys(bus));
console.log('describe :', bus.describe());
console.log('run(10)  :', scaled, '| trips now', bus.trips);
console.log('statics  :', Danfo.fleet, '| Danfo.__proto__ === Vehicle:', Object.getPrototypeOf(Danfo) === Vehicle);
console.log('this before super():', tooEarly);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('super() runs the parent constructor first, so its keys come first', Object.keys(bus), ['plate', 'trips', 'seats']);
test('the override wraps the parent rather than replacing it', bus.describe(), 'danfo vehicle LSD-244-XA with 14 seats');
test('super.run does the parent work and the child scales the result', scaled, 140);
test('the parent still counted the trip', bus.trips, 1);
test('the instance is both classes at once', [bus instanceof Danfo, bus instanceof Vehicle], [true, true]);
test('the parent prototype is in the instance chain', Object.getPrototypeOf(Danfo.prototype) === Vehicle.prototype, true);
test('and the parent class is in the class chain, which is how statics inherit', [Danfo.fleet, Object.getPrototypeOf(Danfo) === Vehicle], ['Lagos', true]);
test('touching this before super() throws a ReferenceError', tooEarly, 'ReferenceError');

extends wires up two chains, not one: Danfo.prototype inherits from Vehicle.prototype so instances find inherited methods, and Danfo itself inherits from Vehicle so Danfo.fleet resolves. The second chain is the part people are surprised by, and it is why a static method's this can be a subclass.

The last assertion is not a style rule. In a derived constructor this does not exist until super() returns — the parent is what creates the object — so an early write is a ReferenceError, in the same family as reading a let before its declaration. Note also that super.describe() is resolved against the prototype where the method was written, not against this; that is what stops describe calling itself for ever.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.