在ES6JavaScript类中的非静态成员函数中调用静态getter
如何从es 6类中的普通成员函数调用静态函数 以下是一个例子:在ES6JavaScript类中的非静态成员函数中调用静态getter,javascript,node.js,ecmascript-6,es6-class,Javascript,Node.js,Ecmascript 6,Es6 Class,如何从es 6类中的普通成员函数调用静态函数 以下是一个例子: class Animal { constructor(text) { this.speech = text; } static get name() { return "Animal"; } speak() { console.log( this.name + ":"+ this.speech) } } class Tiger ex
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函数更改为return
speak() {
console.log( Animal.name + ":"+ this.speech)
}
但这将始终从Animal类输出名称,但我想要的是输出当前类的静态名称属性(例如子类中的“Tiger”)。如何执行此操作?将非静态的
get name()
添加到Animal
类,该类返回this.constructor.name
:
get name() {
return this.constructor.name;
}
类动物{
构造函数(文本){
这个。演讲=文本;
}
静态获取名称(){
返回“动物”;
}
获取名称(){
返回this.constructor.name;
}
讲{
console.log(this.name+:“+this.speech)
}
}
虎类动物{
静态获取名称(){
回归“老虎”
}
}
var animal=新动物(“嘿,那里”);
动物。说();
var tiger=新老虎(“你好”);
老虎。说()
您可以使用this.constructor.name
,至少在您的情况下可以使用(静态成员是构造函数函数的属性,在这方面可以帮助您)。但是,我不确定这是否是最好/最干净的解决方案。为什么是静态的?