Search code examples
javascriptclassmethodsstatic-methods

Define method on class and instance in javascript


I want to be able to access a method from both the instance and the class:

class AClass {
  // I want to make this both static and normal
  method() {
    console.log("Method called");
  }
}

I would expect to be able to access static methods from the instance (like in python with @staticmethod) but I can't as it gives an error:

class AClass {
  static method() {
    console.log("Method called");
  }
}

AClass.method();  // this works
(new AClass).method();  // this doesn't work

Similar questions

  • Call static methods from regular ES6 class methods This question is not a duplicate of that question because I want the same name to both a static method and an instance method. That question is about calling a static method from an instance method (different name)

Solution

  • Create a non-static method of the same name and call the static method from the non-static method.

    class AClass {
      static method() {
        console.log("Method called");
      }
      method() {
        AClass.method();
      }
    }
    
    AClass.method();  // this works
    (new AClass).method();  // this now works