Recently, a new proposal was introduced that would introduce private variables and methods to classes. Currently, it is at stage-3.
Its very simple, just put # before the name of variables or method, and it becomes private.
class Person {
#salary = 100;
#increaseSalary() {
this.#salary += 1000;
}
}
let p1 = new Person();
console.log(p1.#salary); //Error - Private name #salary is not defined
console.log(p1.#increaseSalary); //Error - Private name #increaseSalary is not defined
π Live Demo/Playground
π Babel supports this feature in 7.2+ versions out of box.
π You can also enable this feature by just installing these babel plugins -
babel-plugin-proposal-private-methods
babel-plugin-proposal-class-properties
Top comments (0)