Getters, Setters, and Private Fields
Getters and setters allow property-like syntax around custom behavior. Private class fields use the # syntax and are enforced by the language, unlike naming conventions such as _value.
Private fields cannot be accessed with normal property syntax from outside the class. This provides stronger encapsulation than convention-based private properties.
Private State
class BankAccount {
#balance = 0;
deposit(amount) {
if (amount <= 0) throw new Error('Invalid amount');
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.balance);💡 The balance field is private to the class body. External code can use the public getter but cannot directly access #balance.
Key Takeaways
- Getters and setters provide controlled property access.
- Private fields use
#and are enforced by the language. - Encapsulation can protect invariants such as valid account balances.
Knowledge Check
Which syntax defines a JavaScript private class field?