js call static method from class

后端 未结 5 2184
南旧
南旧 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:23

    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 :-)

提交回复
热议问题