Sub topic 3
Static Private Members
This chapter assumes you know class syntax, extends, and the #field basics covered earlier.
Static Private Members
Use static #name for state that belongs to the class itself. A static getter can expose that state without letting outside code write to it.
class Counter {
static #instances = 0;
#count = 0;
constructor() {
Counter.#instances++;
}
increment() {
this.#count++;
return this.#count;
}
static get instances() {
return Counter.#instances;
}
static isCounter(obj) {
return #count in obj;
}
}
const c = new Counter();
c.increment();
console.log(Counter.instances); // 1
console.log(Counter.isCounter(c)); // true
console.log(Counter.isCounter({})); // falseRefer to static private fields as Counter.#instances and not this.#instances. A subclass constructor does not have the field, so this.#instances throws a TypeError when the static method is called on the subclass.
Checking for Private Fields with `#field in obj`
#count in obj returns true only for objects that the class constructor initialized. A look-alike object with a public count property fails the check. This makes it a reliable brand check: it tells you whether an object really is an instance of the class. A plain obj.#count would throw on such objects instead of returning false.
Before #: Underscores, Closures, and WeakMaps
| Pattern | Really private? | Cost |
|---|---|---|
| `this._x` | No, only a naming convention | None |
| Closure variables | Yes | Methods are created again for every instance |
| Module `WeakMap` | Yes | More verbose, and each lookup goes through the map |
| `#x` | Yes, enforced by the language | Breaks with Proxies |
const secrets = new WeakMap();
class Wallet {
constructor(amount) { secrets.set(this, amount); }
get amount() { return secrets.get(this); }
}
console.log(new Wallet(10).amount); // 10Accessors and Private State Across Subclasses
A getter and its setter together form one property. If a subclass overrides only the getter, it replaces the whole property, and the inherited setter disappears.
class Base {
#value = 1;
get value() { return this.#value; }
set value(v) { this.#value = v; }
}
class Derived extends Base {
get value() { return super.value * 10; }
set value(v) { super.value = v; } // re-declare to keep writes working
}
const d = new Derived();
d.value = 2;
console.log(d.value); // 20Private fields are not inherited by name. Derived cannot write this.#value. It has to go through Base's accessors.
Common Pitfalls and How to Avoid Them
- Recursive setter. If
set name(v) { this.name = v; }assigns to its own property, it calls itself until the stack overflows. Store the value in#nameinstead. - Serialization.
JSON.stringifyskips accessors on the prototype and skips private fields. Add atoJSON()method to control the output. - Proxies. A getter called through a
Proxyruns withthisset to the proxy, and the proxy has no#field, so the read throws aTypeError. Bind methods to the target, or avoid proxying classes that use private fields.
Exercise
A subclass defines only get value() over a base class that has both a getter and a setter. What happens when you assign instance.value = 5 in strict mode, and how do you fix it?
Show answer
The assignment throws a TypeError. The subclass's accessor has no setter, and it shadows the base property. Fix it by also defining set value(v) { super.value = v; } in the subclass.
Exercise
Why is #count in obj safer than obj instanceof Counter for checking that an object is a real Counter?
Show answer
instanceof only checks the prototype chain, which Object.create(Counter.prototype) or Object.setPrototypeOf can fake. #count in obj is true only if the Counter constructor actually initialized the object.