Search code examples
javascriptclassoopprivate

Class private method in newest chrome


I have newest google chrome currently version 80.0.3987.87. I copied example from JS docs which is

class ClassWithPrivateMethod {
  #privateMethod() {
    return 'hello world'
  }

  getPrivateMessage() {
      return #privateMethod()
  }
}

const instance = new ClassWithPrivateMethod()
console.log(instance.getPrivateMessage())
// expected output: "hello worl​d"

and paste it to console. I should get Hello World but instead I have error:

Uncaught SyntaxError: Unexpected token '('

from second line where I declare private method. Why error, what is wrong with my environment? I don't think MDN docs are incorrect..


Solution

  • Update: It is now supported by chrome. the same example will work on chrome devtools if you add this to getPrivateMessage method: getPrivateMessage() { return this.#privateMethod(); }

    As far as I can tell the proposal is still just stage 3
    you can check here Development history & status
    for more details about the process
    MDN only says that chrome supports private class fields not methods.
    That's the reason you get an error.
    However, as mentioned private fields are supported by chrome and you can use something similar to that :

    class ClassWithPrivateMethod {
      #privateMethod
    
      constructor(){
          this.#privateMethod = function(){
              return 'hello world';
          };
      }
    
      getPrivateMessage() {
          return this.#privateMethod();
      }
    }
    const instance = new ClassWithPrivateMethod();
    console.log(instance.getPrivateMessage());