1

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?

2
  • 1
    You could use this.constructor.name, at least in your case that would work (static members are properties of the constructor function and Object.prototype.constructor is helping you there). However, i am unsure whether that is the best/cleanest solution. Commented Jan 4, 2017 at 14:37
  • Why is it static? Commented Jan 4, 2017 at 14:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.