Call static getter within a non static member function in es6 javascript class

1.4k views Asked by At

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?

1

There are 1 answers

0
Ori Drori On BEST ANSWER

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();