0 day streak
javascript / intermediate
Snippet

Private Class Fields and Methods

Private class fields (starting with #) ensure that internal data and methods cannot be accessed or modified from outside the class instance, providing true encapsulation.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SecureVault {
#secretKey;
constructor(key) {
this.#secretKey = key;
}
#hashKey() {
return `hash_${this.#secretKey}`;
}
getAccess() {
return this.#hashKey();
}
}
const vault = new SecureVault('12345');
console.log(vault.getAccess()); // Works
// console.log(vault.#secretKey); // SyntaxError
Breakdown
1
#secretKey;
Declares a private field that is inaccessible outside the class.
2
#hashKey() { ... }
Defines a private method that can only be called by other methods within the same class.