Calling an overridden static method from parent

前端 未结 2 1571
不思量自难忘°
不思量自难忘° 2021-02-18 16:40

First, some code to set the stage:

var instances = [];

class Parent {
    static doImportantStuff() {
        console.log( \'Parent doing important stuff\' );
          


        
2条回答
  •  梦如初夏
    2021-02-18 17:32

    If you don't want to call

    Child1.doImportantStuff();
    

    in Parent, but rather dynamically invoke the overridden static method, you can do:

    this.constructor.doImportantStuff();
    

    This also works for setters and in the constructor of the parent class:

    class Parent {
        static get foo() {
            // Throw an error to indicate that this is an abstract method.
            throw new TypeError('This method should be overridden by inheriting classes.');
        }
    
        constructor() {
            console.log(this.constructor.foo);
        }
    
        logFoo() {
            console.log(this.constructor.foo);
        }
    }
    
    class Child extends Parent {
        static get foo() {
            return 'yay';
        }
    }
    
    const child = new Child(); // Prints 'yay'
    child.logFoo(); // Prints 'yay'

提交回复
热议问题