How to inherit static methods from base class in JavaScript?

后端 未结 6 1595
长情又很酷
长情又很酷 2020-12-24 07:53

I\'m trying to achieve some basic OOP in JavaScript with the prototype way of inheritance. However, I find no way to inherit static members (methods) from the base class.

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 07:58

    you can access static fields via this.constructor[staticField];

    class A {
      static get Foo() { return 'Foo'; }
      
      constructor() {
        console.log(`Class ${this.constructor.name}`, this.constructor.Foo);
      }
    }
    
    class B extends A {
        static get Foo() { return 'Baz'; }
    }
    
    class C extends A {}
    
    const a = new A();
    const b = new B();
    const c = new C()

提交回复
热议问题