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

2 Answers 2

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).

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

Comments

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

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.