js从类中调用静态方法

Chr*_*ris 20 javascript static class this

我有一个静态方法的类:

class User {
  constructor() {
    User.staticMethod();
  }

  static staticMethod() {}
}
Run Code Online (Sandbox Code Playgroud)

对于静态方法是否有这样的东西(即引用没有实例的当前类).

this.staticMethod()
Run Code Online (Sandbox Code Playgroud)

所以我不必写类名'User'.

Nin*_*eer 35

来自MDN文档

静态方法调用直接在类上进行,并且在类的实例上不可调用.静态方法通常用于创建实用程序功能.

有关详细信息,请参阅=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

你可以这样做=> this.constructor.staticMethod());来调用静态方法.

class StaticMethodCall {
  constructor() {
    console.log(StaticMethodCall.staticMethod()); 
    // 'static method has been called.' 

    console.log(this.constructor.staticMethod()); 
    // 'static method has been called.' 
  }

  static staticMethod() {
    return 'static method has been called.';
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 它们之间的区别在于继承。`this.constructor.staticMethod()` 在子类上使用静态方法,因此可以被重写,而 `StaticMethodCall.staticMethod()` 无论继承如何都使用相同的方法,并且如果不重写方法就无法被重写那叫它。 (11认同)
  • 哪种方式更可取? (2认同)
  • @OlehZiniak 我更喜欢`ClassName.StaticMethod()` (2认同)
  • 还要考虑匿名类。`this.constructor.staticMethod()` 将在那里工作。 (2认同)

小智 6

User.staticMethod()您可以使用:this.constructor.staticMethod()