js call static method from class

2019-01-19 12:33发布

问题:

I have a class with a static method:

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

  static staticMethod() {}
}

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

this.staticMethod()

so I don't have to write the class name 'User'.

回答1:

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


回答2:

static things bind to class rather than instance. So you must at least specify the class name.

If you don't want to bind to them to a class make them global.



回答3:

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