1

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();
    }
}
Community
  • 1
  • 1
Kevin Farrugia
  • 6,431
  • 4
  • 38
  • 61
  • As I understand it - a static method gives you the ability to call that method without instantiating a "new Class". On the other hand you would need to type "new Class" in order to be able to call nonStaticMethod(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static Can you make a utility class separate from the nonStaticMethod class and then you call Utils.staticMethod() inside your nonStaticMethod? – Spencer Bigum Apr 27 '17 at 16:39
  • 1
    Is there a reason you cannot introduce an auxiliray name after the `export default class` (like `export default class Foo`) and refer to the static method with the name? (`Foo.staticMethod`)? Would this work for you? – Wiktor Zychla Apr 27 '17 at 16:41
  • 2
    Possible duplicate of [es6 call static methods](http://stackoverflow.com/questions/28627908/es6-call-static-methods) – Estus Flask Apr 27 '17 at 16:47
  • @WiktorZychla yes this seems to be working actually. I was not aware that when using default you could also use an class name. – Kevin Farrugia Apr 27 '17 at 16:51
  • I will make an answer out of this comment, then. – Wiktor Zychla Apr 27 '17 at 16:53

2 Answers2

4

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

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

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

export default class _ {

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

  nonStaticMethod(){
      _.staticMethod();
  }
}
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106