如何从 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
我可以将说话功能更改为返回
speak() {
console.log( Animal.name + ":"+ this.speech)
}
但这总是会输出 Animal 类的名称,但我想要的是输出当前类的静态名称属性(例如子类中的“Tiger”)。我该怎么做?
最佳答案
将非静态get name()
添加到返回this.constructor.name
的Animal
类:
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();
关于javascript - 在 es6 javascript 类的非静态成员函数中调用静态 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41466282/