How can i call a static function from a normal member function within an es 6 class?
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
:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.