Search code examples
javascriptclassecmascript-6private-memberses2022

Private properties in JavaScript ES6 classes


Is it possible to create private properties in ES6 classes?

Here's an example. How can I prevent access to instance.property?

class Something {
  constructor(){
    this.property = "test";
  }
}

var instance = new Something();
console.log(instance.property); //=> "test"

Solution

  • Private class features is now supported by the majority of browsers.

    class Something {
      #property;
    
      constructor(){
        this.#property = "test";
      }
    
      #privateMethod() {
        return 'hello world';
      }
    
      getPrivateMessage() {
          return this.#property;
      }
    }
    
    const instance = new Something();
    console.log(instance.property); //=> undefined
    console.log(instance.privateMethod); //=> undefined
    console.log(instance.getPrivateMessage()); //=> test
    console.log(instance.#property); //=> Syntax error