我是类及其子类,需要从父类调用子级的静态方法。但是,如何在不知道哪个孩子的情况下调用静态方法呢?

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

最佳答案

调用上下文是Human类,而talk方法是直接在其上的属性,因此您只需调用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())

09-30 10:13