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