📘super

JSvalueobjectclassinheritance ⟩ super

// in any method definition
super.prop        // parent's property
super[expr]       // (same)

// in subclass constructor
super(...args)    // superclass constructor

super

👉 see: JavaScript.info

💾 程式: replit

// superclass
class A {

    constructor(name) {
        this.speed = 0;
        this.name = name;
    }

    // ⭐ super.stop()
    stop() {
        this.speed = 0;
        log(`${this.name} stands still.`);
    }

}


class B extends A {
    
    // ✅ OK
    stop() {
        // ---------------------------------------------------
        // • arrow function doesn't have its own `super`.
        // • if accessed, it’s taken from the outer function.
        // ---------------------------------------------------
        // ⭐ call `super.stop()` after 1 sec
        //         ╭── arrow func ──╮
        setTimeout(() => super.stop(), 1000);    
    }
    
    // ❌ doesn't work
    stop2() {
        //          ╭──── ❌ regular func ───╮
        setTimeout( function(){ super.stop() }, 1000);
        //                      ^^^^^
        // ⛔ SyntaxError: 'super' keyword unexpected here.
    }
}

new B("Bunny").stop();    // "Bunny stands still." (after 1 sec)

Last updated

Was this helpful?