Private class fields with # work but WeakMap provides better encapsulation and no memory leaks.
Private Fields Approach:
class Counter {
#count = 0; // Private
increment() { this.#count++; }
get value() { return this.#count; }
}
WeakMap Approach:
const _private = new WeakMap();
class Counter {
constructor() {
_private.set(this, { count: 0, history: [] });
}
increment() {
const data = _private.get(this);
data.history.push(data.count);
data.count++;
}
get value() {
return _private.get(this).count;
}
get history() {
return [..._private.get(this).history];
}
}
const c = new Counter();
c.increment();
console.log(c.value); // 1
// c._private undefined - truly private!
Memory Advantage: When Counter instance is garbage collected, WeakMap entry automatically removed!
