JS: Class Private Fields and Methods
What is private elements
in the body of a class,
class ClassName {body}
Private elements are names that start with hash #.
example
#var_name;#var_name = value;#method_name (params) {body}get #getter_name () {body}set #setter_name (params) {body}
static elements can also be private.
Scope of private elements
Private elements are only visible within the class body.
Access private elements
Private instance elements
this.#var_namefor instance variablethis.#method_name(arg)for instance methods.
// basic example of private variable class Burger { #secret_sauce = "eggs and milk"; show_sauce() { return this.#secret_sauce; } } // create a instance const my_burger = new Burger(1); console.log(my_burger.show_sauce()); // "eggs and milk"
Private static elements
Constructor_name.#var_namefor static variableConstructor_name.#method_name(arg)for static methods.
🛑 warning: for private static elements, this also works this.#var_name but breaks in subclass.
// basic example of static private variable class Burger { static #secret_sauce = "eggs and milk"; show_sauce() { return Burger.#secret_sauce; } } const my_burger = new Burger(1); console.log(my_burger.show_sauce()); // "eggs and milk"
Private elements are not properties
Private elements are not properties.
You cannot use the bracket notation such as this[#name].
// verify private elements are not properties class Burger { constructor(x) { this.meat = x; } // static private variable static #secret_cheese = 1; // static private method static #add_cheese(x) { return Burger.#secret_cheese + x; } // private variable #secret_sauce = 1; // private method #add_sauce(x) { return this.#secret_sauce + x; } } // s------------------------------ // create a instance const my_burger = new Burger(1); // private elements are not a property of any object console.assert( Reflect.has(Burger, "#secret_sauce") === false, Reflect.has(Burger, "#add_sauce") === false, Reflect.has(Burger, "#secret_cheese") === false, Reflect.has(Burger, "#add_cheese") === false, ); console.assert( Reflect.has(my_burger, "#secret_sauce") === false, Reflect.has(my_burger, "#add_sauce") === false, Reflect.has(my_burger, "#secret_cheese") === false, Reflect.has(my_burger, "#add_cheese") === false, );