16

When I am trying to call a static method from constructor in javascript it says the method doesn't exist.

class TestClass {

    constructor(){
        this.staticMethod();
    }

    static staticMethod() {

    }
}

This works fine if i try to call a normal method from constructor. If static methods belongs to class instead of instance why it's not allowing them to call from constructor?

Ashok
  • 487
  • 5
  • 22

2 Answers2

36
this.constructor.staticMethod()

can be used to avoid referring to the class directly (particularly useful for class inheritance and pasted code).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 1
    This was precisely what I needed. – geoyws Mar 28 '17 at 09:53
  • I know I'm late to this party but is there a difference between `this.constructor.staticMethod()` and `TestClass.staticMethod()`? – Jonathon Nordquist Sep 06 '19 at 21:47
  • 1
    @JonathonNordquist There's no difference, as long as it's called inside TestClass, but there's a difference for inherited classes. – Estus Flask Sep 07 '19 at 06:04
  • I was searching for this exactly. The original poster of the question was only trying to call a static method in a normal way but I needed something that is polymorphic like in Java, when you use the object reference to call a static method instead of the class name and this is the exact answer I needed. Upvoted! – Ilja KO May 09 '22 at 01:56
15

You have to call it like this:

TestClass.staticMethod()
dlopez
  • 969
  • 5
  • 17