Private Class Fields Hide Internal State
Encapsulate state with # fields and # methods: the ledger cannot be read or mutated outside the class, and private keys never leak into Object.keys or JSON.
Code
// # 私有字段只在类内部可见:外部改不了账本,只能走公开方法
class Ledger {
#entries = [];
#id = 0;
record(label, cents) {
this.#entries.push({ id: ++this.#id, label, cents });
return this.#id;
}
total() {
return this.#entries.reduce((sum, e) => sum + e.cents, 0);
}
// 私有方法:内部复用的格式化逻辑
#format(e) {
return '#' + e.id + ' ' + e.label + ' ' + e.cents;
}
audit() {
return this.#entries.map((e) => this.#format(e));
}
}
const ledger = new Ledger();
ledger.record('coffee', 380);
ledger.record('book', 1250);
console.log('total:', ledger.total());
console.log('audit:', ledger.audit());
// 私有性是语言级的:Object.keys 与下标访问都摸不到 #entries
console.log('own keys:', Object.keys(ledger), '| bracket:', ledger['#entries']);Output
Captured from a sandboxed run of this snippet in the build pipeline.
total: 1630
audit: [ '#1 coffee 380', '#2 book 1250' ]
own keys: [] | bracket: undefinedHow the snippet works
The snippet is organized around the class Ledger.
Module-level bindings hold the data — ledger — with no function scope in between.
Using it
Running the file prints labeled results such as total:, audit:, own keys: — each operation’s effect is visible in the output.
Key statements
return this.#entries.reduce((sum, e) => sum + e.cents, 0);
return this.#entries.map((e) => this.#format(e));
return '#' + e.id + ' ' + e.label + ' ' + e.cents;
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `ledger`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.