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:

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

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

If you cannot do this for some reason, 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


Solution 2:

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

export default class _ {

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

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

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