javascript / intermediate
Snippet
Encapsulation with Private Class Fields
Private class fields (using the # prefix) ensure that internal data cannot be accessed or modified from outside the class instance, providing true encapsulation in JavaScript.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class SecureVault {#accessKey;#balance = 0;constructor(key, initialDeposit) {this.#accessKey = key;this.#balance = initialDeposit;}withdraw(key, amount) {if (this.#accessKey !== key) throw new Error('Unauthorized');this.#balance -= amount;return this.#balance;}}
Breakdown
1
#accessKey;
Declares a private field that is inaccessible outside the class body.
2
this.#balance -= amount;
Modifies the private balance only through a controlled public method.