JavaScriptFundamental (ES6), part 1
Private data with WeakMap in JavaScript
82 A WeakMap holding data the object cannot see
hardKeep an account's balance in a WeakMap keyed by the instance instead of on the instance. Show that nothing about the balance appears on the object, that the map cannot be listed or counted, that a primitive key is refused, and that a look-alike object handed to a method is caught rather than served.
Stuck? Three hints, smallest first
- 1. The instance is the key:
store.set(this, { kobo })in the constructor,store.get(this)in every method. - 2. A
WeakMaphasget,set,hasanddeleteand nothing else — nosize, no iteration, nokeys. - 3. Keys must be objects or symbols, which is what makes the "weak" part possible.
const store = new WeakMap();
const registered = new WeakSet();
class Account {
constructor(holder, kobo) {
this.holder = holder;
store.set(this, { kobo });
registered.add(this);
}
get kobo() {
return store.get(this).kobo;
}
credit(kobo) {
const state = store.get(this);
if (!state) throw new TypeError('not an account this ledger knows');
state.kobo += kobo;
return this;
}
}
const one = new Account('Adaeze', 150000);
const two = new Account('Bola', 20000);
one.credit(50000);
const balances = [one.kobo, two.kobo];
const nothingOnTheObject = [Object.keys(one), JSON.stringify(one), Object.getOwnPropertyNames(one)];
const noApi = [typeof store.size, typeof store[Symbol.iterator], typeof store.keys, typeof store.forEach];
let primitiveKey;
try {
store.set('Adaeze', { kobo: 1 });
} catch (error) {
primitiveKey = error.constructor.name;
}
const symbolKeysAreFine = (() => {
const tag = Symbol('tag');
const wm = new WeakMap();
wm.set(tag, 'held');
return wm.get(tag);
})();
const impostor = Object.create(Account.prototype);
impostor.holder = 'Nobody';
let refused;
try {
impostor.credit(1);
} catch (error) {
refused = error.constructor.name;
}
const membership = [registered.has(one), registered.has(impostor), store.has(one)];
const forgotten = new Account('Chidi', 100);
const removed = store.delete(forgotten);
const afterDelete = [store.has(forgotten), store.get(forgotten) === undefined];
console.log('balances:', balances);
console.log('object :', nothingOnTheObject);
console.log('api :', noApi, '| primitive key:', primitiveKey);
console.log('brand :', membership, '| refused:', refused, '| deleted:', removed, afterDelete);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the balance is readable through the instance but not stored on it', balances, [200000, 20000]);
test('nothing about it shows in keys, in JSON, or in own property names', nothingOnTheObject, [['holder'], '{"holder":"Adaeze"}', ['holder']]);
test('a WeakMap has no size, no iteration and no way to list its keys', noApi, ['undefined', 'undefined', 'undefined', 'undefined']);
test('a string cannot be a key, because there is nothing to hold weakly', primitiveKey, 'TypeError');
test('a symbol can, which is the one non-object key allowed', symbolKeysAreFine, 'held');
test('an object made from the prototype was never registered, so the method refuses it', refused, 'TypeError');
test('a WeakSet answers the same question as a yes-or-no brand', membership, [true, false, true]);
test('and delete removes an entry outright', [removed, afterDelete], [true, [false, true]]);
Keying a map by the instance inverts where private data lives: the object holds nothing, the map holds everything, and the only way in is a reference to the object itself. That gives you privacy that survives reflection — no key in Object.keys, nothing in JSON.stringify, nothing in getOwnPropertyNames — which is how libraries kept state private for years before # fields existed, and how they still do it when the state must be attached to an object they did not create.
The missing API is the price and the point. No size, no keys, no iteration, because any of those would let you observe whether the garbage collector has run. An entry lives exactly as long as its key lives: drop the last reference to an account and the balance becomes unreachable and collectable, with no cleanup code and no leak. A plain Map in the same position holds its keys alive for ever, which is the classic cache-shaped memory leak.
Two practical notes. Keys must be objects or symbols, so a string id cannot be a WeakMap key. And store.get(this) returning undefined is a usable brand check: an object built with Object.create(Account.prototype) has the right prototype and no entry, so the method can refuse it — the same job #field in obj does for a class with real private fields.