[英]Call static getter within a non static member function in es6 javascript class
如何在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)
}
但這總是從動物類中輸出名稱,但是我想要的是輸出當前類的靜態名稱屬性(例如,子類中的“老虎”)。 我怎樣才能做到這一點?
向返回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.