javascript - JS从类中调用静态方法

标签 javascript class static this

我有一个带有静态方法的类:

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

  static staticMethod() {}
}

静态方法是否有与此等效的方法(即引用没有实例的当前类)?

this.staticMethod()

所以我不必写类名:“User”。

最佳答案

来自 MDN 文档

Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility functions.

更多请参见=> 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.';
  }
}

关于javascript - JS从类中调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614131/

相关文章:

c++ - 字段 ‘value’ 的类型不完整

objective-c - 为什么给单例的静态变量赋了一个nil

java - 声明一个最终的静态方法是个坏主意吗?

javascript - 当名称和值之间有空格字符时如何获取属性数组?

javascript - 5 里后不再显示并放置 `...`

javascript - React 的 onMouseMove 在 div 上工作但不在自定义组件上工作?

android - 从 Alertdialog 启动另一个 Activity

javascript - 获取IE中iframe(打开设计模式)内插入符位置的父元素

c++ - 遍历 txt 文件中的对象数组

python - 使用继承、实例化、*args、**kwargs 混淆代码