Private Fields and Methods
JS · Classes & OOPsyntax
class C {
#privateField = value;
#privateMethod() { ... }
}example
class BankAccount {
#balance = 0;
constructor(initial) {
this.#balance = initial;
}
deposit(amount) {
this.#validateAmount(amount);
this.#balance += amount;
}
get balance() {
return this.#balance;
}
#validateAmount(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
}
}
const acct = new BankAccount(100);
acct.deposit(50);
console.log(acct.balance); // 150
// acct.#balance; // SyntaxErrorNote Private fields/methods use the # prefix. They are truly private -- not accessible outside the class, even by subclasses. instanceof checks still work.