Sub topic 9
Encapsulation with Private Fields and Methods
This chapter assumes you already know how to declare public instance fields, write getters and setters, and define static members. You should also be comfortable with extends at a basic level. Earlier chapters covered all of these.
Encapsulation means hiding an object's internal state so that outside code can only change it through methods you control. JavaScript developers used to rely on conventions such as a leading underscore (this._balance), which hid nothing. Private class members, written with a # prefix, give real privacy that the language enforces.
Declaring Private Fields and Methods
A private field is a class field whose name starts with #. You must declare it in the class body. After that, only code inside that class body can read or write it. Private methods and accessors use the same prefix.
class BankAccount {
#balance = 0;
#history = [];
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
this.#assertPositive(amount);
this.#balance += amount;
this.#history.push({ type: 'deposit', amount });
return this;
}
withdraw(amount) {
this.#assertPositive(amount);
if (amount > this.#balance) {
throw new RangeError('Insufficient funds');
}
this.#balance -= amount;
this.#history.push({ type: 'withdraw', amount });
return this;
}
get balance() {
return this.#balance;
}
get #transactionCount() {
return this.#history.length;
}
summary() {
return `${this.owner}: ${this.#balance} after ${this.#transactionCount} transactions`;
}
#assertPositive(amount) {
if (!Number.isFinite(amount) || amount <= 0) {
throw new RangeError(`Invalid amount: ${amount}`);
}
}
}
const acct = new BankAccount('Ada');
acct.deposit(100).withdraw(30);
console.log(acct.balance); // 70
console.log(acct.summary()); // 'Ada: 70 after 2 transactions'
console.log(Object.keys(acct)); // [ 'owner' ]
console.log(JSON.stringify(acct)); // '{"owner":"Ada"}'
console.log(acct['#balance']); // undefinedHere is what this example shows:
#balanceand#historyare per-instance private fields. Their initializers run for every new object, just like public fields.#assertPositiveis a private method. Like a public method, it is defined once and shared by all instances. Outside code cannot call it.get #transactionCountis a private getter. You can also write private setters and privatestaticmembers.- A public getter,
balance, exposes the value as read-only. This is the usual pattern: keep the state private and expose only what callers need. - Private members never show up in
Object.keys,for...in,JSON.stringify, orObject.getOwnPropertyNames. They are not properties at all. acct['#balance']looks up an ordinary string-keyed property called"#balance", which does not exist. A private name cannot be reached with bracket notation or built dynamically.
How Privacy Is Enforced
Private names are lexically scoped. The JavaScript engine checks every #name you write against the class bodies that enclose it, and it does this when it parses the file, before any code runs. This gives you two distinct kinds of failure.
The first check makes outside access impossible to write at all:
class Secret {
#code = 1234;
}
const s = new Secret();
console.log(s.#code); // SyntaxError: Private field '#code' must be declared in an enclosing classThe entire script is rejected, including any lines before the bad one. So you cannot work around the check with try...catch.
The second check happens at runtime. Code inside the class may run against an object that was never built by that class. Privacy belongs to the class, not to a single instance, so one instance can read another instance's private fields:
class Money {
#cents;
constructor(cents) {
this.#cents = cents;
}
equals(other) {
return #cents in other && this.#cents === other.#cents;
}
static add(a, b) {
return new Money(a.#cents + b.#cents);
}
toString() {
return `$${(this.#cents / 100).toFixed(2)}`;
}
}
const price = new Money(150);
console.log(price.equals(new Money(150))); // true
console.log(price.equals({ cents: 150 })); // false
console.log(String(Money.add(price, new Money(25)))); // '$1.75'
try {
Money.add(price, { cents: 25 });
} catch (err) {
console.log(err instanceof TypeError); // true
}The #cents in other expression is a brand check. It returns true only if other was initialized by Money's field definitions. It does not throw for foreign objects, so it is the safe way to guard against them. Its right-hand side must still be an object, though: #cents in 5 throws a TypeError.
Private Members and Inheritance
A subclass instance does carry its parent's private fields, because the parent's field initializers run on it. The subclass's code cannot name them, though, because #secret is declared in the parent's class body and not in the child's.
class Base {
#secret = 42;
reveal() {
return this.#secret;
}
}
class Child extends Base {
#secret = 'unrelated';
peek() {
return [this.reveal(), this.#secret];
}
}
console.log(new Child().peek()); // [ 42, 'unrelated' ]Child declares its own #secret, and that name is a separate private name. It does not override or collide with the parent's field. Each instance of Child holds both fields. If a subclass needs to reach parent state, the parent must provide a method or accessor for it. JavaScript has no protected modifier. Some teams fall back on the _name convention for members that subclasses are meant to use.
Gotcha: a parent constructor calling an overridden method
Fields are installed in a fixed order. In a base class, they are installed before the constructor body runs. In a derived class, they are installed right after super() returns. If the parent constructor calls a method that the child overrides, the child's private fields do not exist yet:
class Widget {
constructor() {
this.render();
}
render() {}
}
class Label extends Widget {
#text = 'hello';
render() {
console.log(this.#text);
}
}
new Label(); // TypeError: Cannot read private member #text from an object whose class did not declare itThe same call order with a public field would quietly log undefined. With a private field you get a loud TypeError, which is arguably better. Either way, the fix is to avoid calling overridable methods from a constructor.
Gotcha: `this` in static private access
Static private members belong only to the class constructor that declared them. A subclass constructor does not get its own copy, and it does not inherit the parent's:
class Plugin {
static #registry = new Map();
static register(name) {
Plugin.#registry.set(name, this); // use Plugin, not this
}
static lookup(name) {
return Plugin.#registry.get(name);
}
}
class Fancy extends Plugin {}
Fancy.register('fancy');
console.log(Plugin.lookup('fancy') === Fancy); // trueIf you wrote this.#registry, then Fancy.register(...) would run with this === Fancy, and it would throw a TypeError because Fancy has no #registry slot.
Proxies and Other Edge Cases
A Proxy does not forward private access to the object it wraps. When a getter runs with the proxy as this, the private lookup fails:
class Temperature {
#celsius = 20;
get celsius() {
return this.#celsius;
}
}
const proxied = new Proxy(new Temperature(), {});
try {
console.log(proxied.celsius);
} catch (err) {
console.log(err.constructor.name); // 'TypeError'
}This affects libraries that wrap objects in proxies, such as some reactive state systems. If you need classes that work with such tools, either bind the methods to the real target inside the proxy's get trap, or avoid private fields in those classes.
Some other rules are worth knowing:
delete this.#xis aSyntaxError. Private fields cannot be removed.- You cannot declare the same private name twice in one class. The one exception is a getter and setter pair that share a name.
- Private methods cannot be reassigned.
this.#assertPositive = nullthrows aTypeError. - Optional chaining works:
obj?.#xreturnsundefinedifobjis nullish. - Debuggers such as Chrome DevTools and Node's inspector display private fields. Privacy limits what code can do, not what developers can see.
Choosing an Encapsulation Technique
| Technique | Truly hidden | Shared methods on prototype | Subclass access | Works through Proxy |
|---|---|---|---|---|
| `_name` convention | No | Yes | Yes | Yes |
| Closure variables in constructor | Yes | No, methods are created per instance | No | Yes |
| Module-level `WeakMap` keyed by instance | Yes | Yes | Only if the subclass is in the same module | Only if the `WeakMap` is keyed by the real target |
| `#private` members | Yes | Yes | No | No |
For new code, #private is the default choice. It is fast, it is checked when the file is parsed, and it needs no extra setup. Use a WeakMap if code outside a single class body needs to share private state, for example several classes in one module. Use _name if subclasses or proxy-based tools must reach the member.
Exercises
Exercise
Add a private method #log(type, amount) to BankAccount that pushes onto #history. Then add a public history() method that returns a copy of the history, so callers cannot change the private array. Why does returning this.#history directly weaken encapsulation?
Show answer
Define #log(type, amount) { this.#history.push({ type, amount }); }, call it from deposit and withdraw, and write history() { return this.#history.map((entry) => ({ ...entry })); }. Returning this.#history hands out a reference to the private array. Callers could then push to it, splice it, or edit its entries, and the class would not know. A private field protects the binding, not the object it points to.
Exercise
Write a static method Money.isMoney(value) that returns true only for real Money instances and never throws, even for primitives such as 5 or null.
Show answer
Use static isMoney(value) { return typeof value === 'object' && value !== null && #cents in value; }. The typeof and null checks are needed because #cents in value throws a TypeError when value is not an object.
Exercise
A teammate's code fails with "TypeError: Cannot read private member #items from an object whose class did not declare it". The method that throws is called as list.forEach(store.add). What are two possible causes, and how do you tell them apart?
Show answer
First cause: store.add was detached, so this is undefined or some other object, and that object has no #items slot. Fix it with store.add.bind(store) or an arrow function stored in a class field. Second cause: store is a Proxy, or an object not built by the class. Log this inside add and check #items in this to see which case you have. An undefined this points to a lost binding, and a Proxy or plain object points to a foreign receiver.