js call static method from class

我是研究僧i 提交于 2019-11-26 17:13:29

问题


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:


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




回答3:


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.




回答4:


In @Ninjaneer 's accepted answer:

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

this.constructor.staticMethod() will throw an error because you must call the super constructor before accessing this in the constructor.

Assuming you fix this aforementioned issue, no pun intended, I think the only benefit of calling this.constructor.staticMethod() is that you're not dependent on the name of the class -- if it ever changes. However, this benefit is probably insignificant since it only benefits static method calls made from inside the class. Static method calls made externally would have to be something like StaticMethodCall.constructor.staticMethod() which is defeats the purpose and looks silly.

In Summary:

If you plan on using the static method outside of the class, I'd definitely stick with using StaticMethodCall.staticMethod() since it's more idiomatic and concise.

If you only plan on using the static method within the class, then maybe it's ok to to use this.constructor.staticMethod(), but it'll probably confuse other developers and lead them back to this page :-)



来源:https://stackoverflow.com/questions/43614131/js-call-static-method-from-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!