Call static methods from regular ES6 class methods

前端 未结 3 735
说谎
说谎 2020-11-22 15:14

What\'s the standard way to call static methods? I can think of using constructor or using the name of the class itself, I don\'t like the latter since it doesn

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 15:54

    Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect:

    class Super {
      static whoami() {
        return "Super";
      }
      lognameA() {
        console.log(Super.whoami());
      }
      lognameB() {
        console.log(this.constructor.whoami());
      }
    }
    class Sub extends Super {
      static whoami() {
        return "Sub";
      }
    }
    new Sub().lognameA(); // Super
    new Sub().lognameB(); // Sub
    

    Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden.

    This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self.

    If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java, use the explicit reference.

提交回复
热议问题