【问题标题】:How to call a class itself and not its instance in Javascript?如何在Javascript中调用一个类本身而不是它的实例?
【发布时间】:2018-06-21 04:33:41
【问题描述】:

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

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

【问题讨论】:

标签: javascript node.js ecmascript-6


【解决方案1】:

只需从doSomething 静态方法内部调用this.talk()

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

在静态方法的上下文中,this 将引用类对象被调用(禁止任何代码更改它)。

【讨论】:

    【解决方案2】:

    调用上下文是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())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多