Call static methods when using default

僤鯓⒐⒋嵵緔 提交于 2021-02-10 15:41:02

问题


When using ES6 modules and export default class how is it possible to call a static method from another method within the same class? My question refers specifically to when the class is marked as default (unlike es6 call static methods)

The below example illustrates how it is possible to call the static method from a non-static method when not using default, i.e. Test.staticMethod()?

export default class {
    static staticMethod(){
        alert('static');
    }

    nonStaticMethod(){
        // will not work because staticMethod is static.
        // Ordinarily you would use MyClass.staticMethod()
        this.staticMethod();
    }
}

回答1:


You can use this.constructor.… if you dare, but the better solution would be to just name your class:

export default class MyClass {
    static staticMethod(){
        alert('static');
    }

    nonStaticMethod() {
        // Ordinarily you just use
        MyClass.staticMethod();
    }
}

If you cannot do this for some reason1, there's also this hack:

import MyClass from '.' // self-reference

export default class {
    static staticMethod(){
        alert('static');
    }

    nonStaticMethod() {
        // Ordinarily you just use
        MyClass.staticMethod();
    }
}

1: I cannot imagine a good one




回答2:


You can name your exported class and refer to it by the auxiliary name:

export default class _ {

  static staticMethod(){
      alert('static');
  }

  nonStaticMethod(){
      _.staticMethod();
  }
}


来源:https://stackoverflow.com/questions/43663347/call-static-methods-when-using-default

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