javascript / intermediate
Snippet
Private Class State with WeakMap
WeakMap is used to create truly private data for class instances. Unlike private class fields (#), WeakMap stores data externally, keyed by the instance, ensuring the data is garbage collected when the instance is destroyed.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const privates = new WeakMap();class SecureSession {constructor(token) {privates.set(this, { token, createdAt: Date.now() });}getToken() {return privates.get(this).token;}}const session = new SecureSession('secret-123');console.log(session.token); // undefined
nodejs
Breakdown
1
const privates = new WeakMap();
Initializes a WeakMap that will hold private data without preventing garbage collection.
2
privates.set(this, ...)
Associates a private data object with the current instance of the class.
3
privates.get(this)
Retrieves the private data only from within class methods where 'this' is available.