[英]Call static getter within a non static member function in es6 javascript class
How can i call a static function from a normal member function within an es 6 class? 如何在es 6类中从普通成员函数调用静态函数?
Here is an example: 这是一个例子:
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
I could change the speak function to return 我可以将语音功能更改为返回
speak() {
console.log( Animal.name + ":"+ this.speech)
}
But this would always output the name from the Animal Class, but what i want is to output the static name property of the current class (eg "Tiger" within the subclass). 但这总是从动物类中输出名称,但是我想要的是输出当前类的静态名称属性(例如,子类中的“老虎”)。 How can i do that? 我怎样才能做到这一点?
Add a non static get name()
to the Animal
class that returns this.constructor.name
: 向返回this.constructor.name
的Animal
类中添加一个非静态的get name()
:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.