๐Ÿ“˜super

JS โŸฉ value โŸฉ object โŸฉ class โŸฉ inheritance โŸฉ super

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

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

super

  • arrow functions do not have super. (๐Ÿ‘‰ see: Arrow functions revisited)

  • If accessed, itโ€™s taken from the outer function.

๐Ÿ‘‰ 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