在es6 javascript类的非静态成员函数中调用静态getter

我如何从ES 6类中的普通成员函数调用静态函数?

这里是一个例子:

class Animal { constructor(text) { this.speech = text; } static get name() { return "Animal"; } speak() { console.log( this.name + ":"+ this.speech) } } class Tiger extends Animal { static get name() { return "Tiger" } } var animal = new Animal("hey there"); animal.speak(); var tiger = new Tiger("hello"); tiger.speak(); // output: // undefined:hey there // undefined:hello 

我可以改变说话function返回

 speak() { console.log( Animal.name + ":"+ this.speech) } 

但是这总是会输出动物类的名字,但我想要的是输出当前类的静态名称属性(例如在子类中的“老虎”)。 我怎样才能做到这一点?

将一个非静态的get name()到返回this.constructor.nameAnimal类中:

 get name() { return this.constructor.name; } 
 class Animal { constructor(text) { this.speech = text; } static get name() { return "Animal"; } get name() { return this.constructor.name; } speak() { console.log( this.name + ":"+ this.speech) } } class Tiger extends Animal { static get name() { return "Tiger" } } var animal = new Animal("hey there"); animal.speak(); var tiger = new Tiger("hello"); tiger.speak();