Es11 features- private class variables
ES6 introduced classes to make them reusable modules. Everything declared in class can be accessed by other modules. Before ES20, variables are declared enclosure to make them private With Es2020, Private class variables are introduced to allow the variables used in the class only.
Variables are added to the hash symbol to make it for private use in a class. Syntax
#variable
Let’s see an example declaring a private variable in a class.
class HelloWorld {
#message = "How are you?";
getMessage()
{
console.log(this.#message)
}
}
const hello = new HelloWorld()
hello.getMessage() // How are you?
A declared private class variable message with a hash symbol to it
accessing the private fields with the object of the same class
Directing accessing the private variable throws Uncaught SyntaxError: Private field '#
console.log(greeting.#message) // Private name #message returns undefined