js call static method from class

后端 未结 5 2148
南旧
南旧 2020-12-03 16:49

I have a class with a static method:

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

  static staticMethod() {}
}

Is there som

5条回答
  •  情深已故
    2020-12-03 17:30

    From MDN documentation

    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.

    For more please see=> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

    You can do something like this => this.constructor.staticMethod()); to call static method.

    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.';
      }
    }
    

提交回复
热议问题