liveBook · Manning

Private member

As explained in JavaScript in Depth

A class-defined JavaScript property whose name begins with # and which is accessible only from methods of that class.

A JavaScript class can keep state or behavior inaccessible to outside code by prefixing a member name with #. Unlike an underscore naming convention, this is enforced by the language: private members can be accessed only from methods defined on the class. section 5.6 section 5.6.1

The boundary has observable consequences:

  • Private members are not inherited and do not appear in property enumeration or ordinary property-descriptor queries. section 5.6.1
  • Access depends on the matching object as `this`; separating a method from that object and calling it directly fails. section 5.6.1
class SecureDrawer {
  #pinCode;
  constructor(pin) {
    this.#pinCode = pin;
  }
  #validatePin(pin) {
    return this.#pinCode === pin;
  }
  unlock(pin) {
    if (!this.#validatePin(pin)) {
      throw new Error('access denied');
    }
  }
}
const secureDrawer = new SecureDrawer(12345);
console.log(Object.keys(secureDrawer));  #A

The example stores a PIN and validation method privately, then exposes unlocking through a public method. section 5.6.1

How JavaScript in Depth covers it

How deep it goes
Explains access, receiver binding, inheritance, and visibility through enumeration and descriptors, without detailing implementation internals.
Examples
Demonstrates a private PIN and validator in a SecureDrawer class, alongside an enumeration check.
What you can do after
Build encapsulated class state and methods, then recognize why ordinary enumeration does not reveal them.
How it connects
Connects private members to classes, methods, inheritance, and property enumeration.

Also explained in

Compare how 14 books explain private member →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.