override constructor

โœ… case 1๏ผšnone has constructor

// no constructors
class A {}
class B extends A {}

let b = new B();        // โœ… OK

โŒ case 2๏ผšreturning from derived constructor without calling super() first

class A2 {}

class B2 extends A2 {
    constructor(){
        // ---------------------------------------------------
        // โ›” ReferenceError: 
        //   Must call `super()` constructor in derived class 
        //   โ˜ before accessing `this` or 
        //   โ˜‘ returning from derived constructor
        // ---------------------------------------------------
    }
}

let b2 = new B2();

โŒ case 3๏ผšaccessing this before calling super()

class A3 {}

// (accessing `this` before calling `super()`)
class B3 extends A3 {
    constructor(){
        // ---------------------------------------------------
        // โ›” ReferenceError: 
        //   Must call `super()` constructor in derived class 
        //   โ˜‘ before accessing `this` or 
        //   โ˜‘ returning from "derived constructor"
        // ---------------------------------------------------
        this.name = "Joe"
    }
}

let b3 = new B3();

โœ… case 4๏ผš

class A4 {}

class B4 extends A4 {
    constructor(){
        
        // โญ "derived constructor" expects "parent (base) constructor"
        //    to create an empty object and assign it to `this`.
        super();

        // โœ… now it's OK to access `this`.
        this.name = "Joe";
    }
}

let b4 = new B4();
log(b4.name);            // Joe

Last updated