1

I am class and its subclasses, where I am required to call a static method of a child from the parent. But how can I call the static method without knowing which child?

class Animal{
  static doSomething(){
    //How do i call the static talk here?
    //talk()
  }
}

class Human extends Animal{
  static talk(){
    return 'Hello!'
  }
}

class Dog extends Animal{
  static talk(){
    return 'Bark!'
  }
}

Human.doSomething()
Kucl Stha
  • 565
  • 1
  • 6
  • 20
  • Possible duplicate of [Can I use class variables in the parent class's static methods in ES6?](https://stackoverflow.com/q/47504534/218196) – Felix Kling Jun 21 '18 at 06:24

2 Answers2

3

Just call this.talk() from inside the doSomething static method.

class Animal{
  static doSomething(){
    console.log(this.talk());
  }
}

class Human extends Animal{
  static talk(){
    return 'Hello!'
  }
}

class Dog extends Animal{
  static talk(){
    return 'Bark!'
  }
}

Human.doSomething()

In the context of a static method, this will refer to class object was called on (barring any code to change it).

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
2

The calling context is the Human class, and the talk method is a property directly on it, so you simply call this.talk():

class Animal{
  static doSomething(){
    return this.talk();
  }
}

class Human extends Animal{
  static talk(){
    return 'Hello!'
  }
}

class Dog extends Animal{
  static talk(){
    return 'Bark!'
  }
}

console.log(Human.doSomething())
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320