javascript / intermediate
Snippet
Encapsulating Private Data with WeakMap
WeakMap allows associating private data with an object without exposing it via property keys. It also prevents memory leaks because entries are garbage-collected when the object is destroyed.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const internalState = new WeakMap();class SecureVault {constructor(secret) {internalState.set(this, { secret });}getSecret() {return internalState.get(this).secret;}}
nodejs
Breakdown
1
new WeakMap()
Initializes a collection where keys must be objects and are held weakly.
2
internalState.set(this, ...)
Maps the current instance to a private data object.