Calling an overridden static method from parent

前端 未结 2 2111
北恋
北恋 2021-02-18 17:07

First, some code to set the stage:

var instances = [];

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


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-18 17:19

    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'

提交回复
热议问题