Js calling a static method from a class

I have a class with a static method:

class User {

constructor() {
  User.staticMethod();
}

static staticMethod() {

}

}

Is there something similar for static methods (i.e. refer to the current class without an instance).

this.staticMethod()

therefore, I do not need to write the class name "User".

+6
source share
3 answers

From the MDN documentation

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

See => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static for more details

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

static , . .

, .

+1

instead User.staticMethod () you can add this.constructor.staticMethod ()

0
source

Source: https://habr.com/ru/post/1016766/


All Articles