Skip to content Skip to sidebar Skip to footer

Call Static Methods When Using Default

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 cl

Solution 1:

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

exportdefaultclassMyClass {
    staticstaticMethod(){
        alert('static');
    }

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

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

importMyClassfrom'.'// self-referenceexportdefaultclass {
    staticstaticMethod(){
        alert('static');
    }

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

1: I cannot imagine a good one

Solution 2:

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

exportdefaultclass_ {

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

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

Post a Comment for "Call Static Methods When Using Default"