Search code examples
javascriptclassstatic-functions

Unable to call static function inside its own class


How can I call static function inside the class itself? I try self keyword instead of this but I still get error.

class Test {
  static staticFunction() {
    console.log('Inside static function.');
  }
  regularFunction() {
    this.staticFunction();
  }
}

let test = new Test();
test.regularFunction();


Solution

  • You can reference the static function through the class name, like this:

    class Test {
      static staticFunction(input) {
        console.log('Inside static function.');
      }
      regularFunction() {
        Test.staticFunction();
      }
    }
    
    let test = new Test();
    test.regularFunction();