skip to Main Content

I have encountered with something like this:

class Example {
  // ...

  async #privateMethod() {
    return true
  }

  static staticMethod() {
    try {
       // can't access #privateMethod
      this.#privateMethod()
    } catch (error) {
      console.log('error', error);
    }
  }
}

I want to call a private method within the static method, but I can’t access the private method for some reason. What am I doing wrong, please?

2

Answers


  1. In a static method there is nothing like this. This is the instance of an class created with

    myClassInstance = new Classname(); 
    

    And then you call the methods with

    MyClassInstance.myMethod();
    

    In this method you can then use this as a pointer to the myClassInstance.

    A static method is called without such an instance so you have no this and so you can’t call non static methods.

    Login or Signup to reply.
  2. That private method is an instance method, meaning you would need this to be an instance of Example to do this.#privateMethod.

    When running a static method, you don’t have an instance. Instead, this refers to the constructor (the "class").

    This may be an indication that #privateMethod shouldn’t be an instance method after all, as it could do its job without one.

    If this is the case, then just make that private method also static:

    class Example {
      // ...
    
      static async #privateMethod() {
        console.log("running private static method");
        return true;
      }
    
      static staticMethod() {
        try {
          this.#privateMethod()
        } catch (error) {
          console.log('error', error);
        }
      }
    }
    
    Example.staticMethod();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search