Skip to content
Advertisement

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"

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement