Sub topic 9
Encapsulation with Private Fields and Methods
This chapter assumes you already know how to declare class fields, methods, and getters, as covered in earlier chapters. Encapsulation means hiding an object's internal state so that outside code can only change it through methods you control. JavaScript classes support this with private members, which are names that start with #.
Declaring Private Fields and Methods
A private field is declared in the class body with a # prefix. Only code inside the same class body can read or write it. Private methods and private accessors work the same way.
class BankAccount {
#balance = 0;
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
this.#validate(amount);
this.#balance += amount;
return this.#balance;
}
withdraw(amount) {
this.#validate(amount);
if (amount > this.#balance) {
throw new RangeError('Insufficient funds');
}
this.#balance -= amount;
return this.#balance;
}
get balance() {
return this.#balance;
}
#validate(amount) {
if (!Number.isFinite(amount) || amount <= 0) {
throw new RangeError('Amount must be a positive number');
}
}
}
const account = new BankAccount('Ada');
account.deposit(100);
account.withdraw(30);
console.log(account.balance); // 70
console.log(Object.keys(account)); // [ 'owner' ]
console.log(JSON.stringify(account)); // {"owner":"Ada"}
account.balance = 1_000_000; // no setter, so this does nothing (it throws only in strict mode)
console.log(account.balance); // 70The balance getter gives read-only access. Outside code has no way to set #balance directly. It can only change through deposit and withdraw, and both of those run #validate first.
Private members are invisible to reflection. Object.keys, for...in, JSON.stringify, and Object.getOwnPropertyNames never list them.
The Rules the Engine Enforces
#balance is not a property key, and the # is part of the name itself. The engine checks private names in two places.
- At parse time. Writing
account.#balanceoutside the class body is aSyntaxError, so the whole script fails to load. Using a#nameinside the class that the class never declared is also aSyntaxError. - At run time. If a method runs with a
thisthat lacks the private field, the access throws aTypeError.
const deposit = BankAccount.prototype.deposit;
try {
deposit.call({}, 10);
} catch (err) {
console.log(err instanceof TypeError); // true
}Checking for a Private Field with `in`
The expression #field in obj returns true or false and never throws. Use it to test whether an object really came from your class:
class Token {
#secret;
constructor(secret) {
this.#secret = secret;
}
equals(other) {
return #secret in other && other.#secret === this.#secret;
}
}
console.log(new Token('a').equals(new Token('a'))); // true
console.log(new Token('a').equals({ secret: 'a' })); // falseNotice that equals reads other.#secret. Private access is scoped to the class, not to the instance, so any instance's methods can read the private fields of any other instance of the same class.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using `_balance` and assuming it is private | Outside code can still read and change it | Use `#balance` |
| Assigning `this.#x = 1` without declaring `#x` | `SyntaxError` | Declare `#x;` in the class body |
| Reading a parent's `#field` from a subclass | `SyntaxError`, because the name belongs to the parent's body | Expose a getter or method from the parent |
| Wrapping an instance in a `Proxy` | Private access on the proxy throws `TypeError` | Call methods on the real object |
Exercise
Add a method transferTo(other, amount) to BankAccount that moves money into another account by changing other's #balance directly. Make it throw a TypeError if other is not a BankAccount.
Show answer
Inside the class: transferTo(other, amount) { if (!(#balance in other)) throw new TypeError('Target must be a BankAccount'); this.withdraw(amount); other.#balance += amount; } This works because private access is scoped to the class, so the method can write to other.#balance. Calling withdraw first validates the amount and checks for sufficient funds before any money moves.
Exercise
Why does console.log(JSON.stringify(account)) leave out the balance, and how would you include it?
Show answer
JSON.stringify only serializes own enumerable string-keyed properties, and private fields are not properties. To include the balance, add toJSON() { return { owner: this.owner, balance: this.#balance }; } to the class.