Reputation: 123
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 (e.g. "Tiger" within the subclass). How can i do that?
Upvotes: 1
Views: 1408
Reputation: 193130
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();
Upvotes: 2