Sub topic 9
Static Private Members
This chapter assumes you already know how private instance fields (#field) work and how static getters and setters are declared on a class. It shows how to keep class-level state hidden with the same # syntax.
What a static private member is
A static private member is a field or method that belongs to the class constructor itself, not to each instance, and that only code inside the class body can reach. You declare it by putting both static and # on the name:
static #name = value;creates a static private field.static #helper() { ... }creates a static private method.static get #name()andstatic set #name(v)create a static private accessor.
Static private members are useful for counters, caches, registries, and configuration that every instance shares but outside code should not change.
Exposing class-level state through a static getter
The usual pattern is a static private field paired with a public static getter. Outside code can read the value but cannot assign to it.
class Counter {
static #instances = 0;
#count = 0;
constructor() {
Counter.#instances++;
}
increment() {
this.#count++;
return this.#count;
}
static get instances() {
return Counter.#instances;
}
}
new Counter();
new Counter();
console.log(Counter.instances); // 2
Counter.instances = 99; // ignored in sloppy mode (no setter); throws TypeError in strict mode
console.log(Counter.instances); // 2
console.log(Object.keys(Counter)); // []The constructor writes Counter.#instances, using the class name. Instance code cannot write this.#instances, because this there is an instance, and instances do not carry static private fields.
Static private methods
A static private method holds helper logic that the class uses internally but does not want in its public API. Factory functions and validators are common examples.
class Temperature {
static #MIN_KELVIN = 0;
static #toKelvin(celsius) {
return celsius + 273.15;
}
#celsius;
constructor(celsius) {
if (Temperature.#toKelvin(celsius) < Temperature.#MIN_KELVIN) {
throw new RangeError('Below absolute zero');
}
this.#celsius = celsius;
}
static fromFahrenheit(f) {
return new Temperature((f - 32) * 5 / 9);
}
get celsius() {
return this.#celsius;
}
}
console.log(Temperature.fromFahrenheit(212).celsius); // 100
try {
new Temperature(-300);
} catch (err) {
console.log(err.message); // 'Below absolute zero'
}
// Temperature.#toKelvin(0); // SyntaxError outside the class bodyThe subclass gotcha: use the class name, not `this`
Inside a static method, this is whatever constructor the method was called on. If a subclass calls an inherited static method that reads this.#field, the lookup runs against the subclass constructor. The subclass constructor does not have the field, so the lookup throws a TypeError.
class Config {
static #settings = { debug: false };
static get debugUnsafe() {
return this.#settings.debug; // depends on `this`
}
static get debug() {
return Config.#settings.debug; // always the base class
}
}
class AppConfig extends Config {}
console.log(AppConfig.debug); // false
try {
AppConfig.debugUnsafe;
} catch (err) {
console.log(err instanceof TypeError); // true
}This is unlike public static fields. With a public static field, AppConfig.x falls back to Config.x through the prototype chain. Private names never go through the prototype chain. A private field exists only on the object it was installed on, and static private fields are installed only on the class that declares them.
Quick reference
| Declaration | Lives on | Accessed as |
|---|---|---|
| `#x = 0` | each instance | `this.#x` in instance code |
| `static #x = 0` | the class constructor | `ClassName.#x` |
| `static #f() {}` | the class constructor | `ClassName.#f()` |
| `static get #x()` | the class constructor | `ClassName.#x` |
Exercise
A class Registry has static #items = [] and static add(item) { this.#items.push(item); }. A subclass PluginRegistry extends Registry {} calls PluginRegistry.add('a'). What happens, and how do you fix it?
Show answer
It throws a TypeError. Inside add, this is PluginRegistry, and PluginRegistry has no #items field, because private names are not inherited through the prototype chain. Change the method to use Registry.#items.push(item) so it always targets the base class's field.
Exercise
Why can outside code not reset Counter's instance count to 0, even though Counter.instances is readable?
Show answer
The count is stored in the static private field #instances, which only code inside the class body can reach. The public static getter instances has no matching setter, so assigning to it does nothing in sloppy mode and throws a TypeError in strict mode.