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();
    }
}
5
  • 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(). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Can you make a utility class separate from the nonStaticMethod class and then you call Utils.staticMethod() inside your nonStaticMethod? Commented Apr 27, 2017 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? Commented Apr 27, 2017 at 16:41
  • 2
    Possible duplicate of es6 call static methods Commented Apr 27, 2017 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. Commented Apr 27, 2017 at 16:51
  • I will make an answer out of this comment, then. Commented Apr 27, 2017 at 16:53

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

export default class _ {

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.