Sub topic 9
Static Private Members
This chapter assumes you already know how instance private fields (#field) work and how static getters and setters attach to the class itself. It also assumes you know that extends links a subclass constructor to its parent constructor through the prototype chain. With that in place, this chapter combines the two ideas: private members that belong to the class, not to its instances.
What a static private member is
A static private member is a field, method, or accessor declared with both static and a # name. It lives on the class constructor function. Only code written inside that class body can reach it.
There are three kinds:
| Declaration | Kind | Accessed as |
|---|---|---|
| `static #count = 0;` | Static private field | `ClassName.#count` |
| `static #validate(x) { ... }` | Static private method | `ClassName.#validate(x)` |
| `static get #total() { ... }` | Static private getter | `ClassName.#total` |
| `static set #total(v) { ... }` | Static private setter | `ClassName.#total = v` |
You use them for class-level state that callers should not touch directly. Typical examples are ID counters, caches, registries, configuration, and helper functions that only the class needs.
A class-level ID counter and registry
The example below gives each Ticket a unique ID and keeps a registry of every ticket created. The counter and the registry are both static private fields. Public static methods and a static getter provide controlled, read-only access.
class Ticket {
static #nextId = 1;
static #issued = new Map();
#id;
constructor(title) {
this.#id = Ticket.#nextId++;
this.title = title;
Ticket.#issued.set(this.#id, this);
}
get id() {
return this.#id;
}
static get issuedCount() {
return Ticket.#issued.size;
}
static find(id) {
return Ticket.#issued.get(id) ?? null;
}
}
const a = new Ticket('Fix login');
const b = new Ticket('Update docs');
console.log(a.id, b.id); // 1 2
console.log(Ticket.issuedCount); // 2
console.log(Ticket.find(2).title); // 'Update docs'
console.log(Ticket.find(99)); // null
console.log(Object.keys(Ticket)); // []
console.log('nextId' in Ticket); // false
Ticket.nextId = 1000; // creates an unrelated public property
console.log(new Ticket('New').id); // 3Here are the points to notice:
- The constructor is instance code, but it can still read and write
Ticket.#nextId. Static private members can be reached from any code inside the class body, including instance methods and constructors. Object.keys(Ticket)is empty. Private names are not properties, so reflection does not find them.- Assigning
Ticket.nextId = 1000creates a new public property. It has no connection to#nextId, so the counter cannot be reset from outside.
Static private methods and accessors
Static private methods hold helper logic for the class's static API. Static private accessors compute values from private state. The Logger below validates its level through a private method and uses a private getter to work out a numeric threshold.
class Logger {
static #levels = ['debug', 'info', 'warn', 'error'];
static #level = 'info';
static #isValid(level) {
return Logger.#levels.includes(level);
}
static get #threshold() {
return Logger.#levels.indexOf(Logger.#level);
}
static get level() {
return Logger.#level;
}
static set level(value) {
if (!Logger.#isValid(value)) {
throw new RangeError(`Unknown level: ${value}`);
}
Logger.#level = value;
}
static log(level, message) {
if (!Logger.#isValid(level)) {
throw new RangeError(`Unknown level: ${level}`);
}
if (Logger.#levels.indexOf(level) >= Logger.#threshold) {
console.log(`[${level}] ${message}`);
}
}
}
Logger.log('debug', 'hidden'); // nothing printed
Logger.log('warn', 'disk low'); // [warn] disk low
Logger.level = 'debug';
Logger.log('debug', 'visible'); // [debug] visible
try {
Logger.level = 'verbose';
} catch (err) {
console.log(err.message); // Unknown level: verbose
}
console.log(Logger.level); // 'debug'The public static setter level works as the class's validation gate, just as an instance setter guards an instance private field. The #threshold getter is private because callers have no reason to depend on the numeric index. Keeping it private means you can change how levels are ranked without breaking anyone's code.
The subclass trap: `this.#x` in static methods
This is the most common mistake with static private members. Inside a static method, this is the constructor the method was called on. When a subclass calls an inherited static method, this is the subclass. The subclass does not have the parent's static private field.
class Base {
static #count = 0;
static increment() {
return ++this.#count; // depends on which constructor `this` is
}
}
class Sub extends Base {}
console.log(Base.increment()); // 1
try {
Sub.increment();
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message);
// e.g. "Cannot read private member #count from an object whose class did not declare it"
}Why does this fail? Public static properties are found through the prototype chain: Object.getPrototypeOf(Sub) === Base, so Sub.someStatic falls back to Base.someStatic. Private names never use the prototype chain. A static private field is installed once, directly on the constructor that declares it. When this is Sub, the lookup of #count on Sub finds nothing and throws.
The fix is to name the class explicitly instead of using this:
class Base {
static #count = 0;
static increment() {
return ++Base.#count;
}
static get count() {
return Base.#count;
}
}
class Sub extends Base {}
Base.increment();
Sub.increment();
console.log(Base.count); // 2
console.log(Sub.count); // 2: one shared counterBase and Sub now share one counter. If you want each subclass to have its own counter, static private fields are the wrong tool. Use a private Map keyed by constructor instead:
class Base {
static #counts = new Map();
static increment() {
const next = (Base.#counts.get(this) ?? 0) + 1;
Base.#counts.set(this, next);
return next;
}
}
class Sub extends Base {}
Base.increment();
Sub.increment();
Sub.increment();
console.log(Base.increment()); // 2
console.log(Sub.increment()); // 3The same trap exists in instance code. this.constructor.#count fails for instances of a subclass, because this.constructor is the subclass. Write Base.#count there as well.
Static initialization blocks
Sometimes a static private field needs setup logic that does not fit in one initializer expression. A static initialization block, written static { ... }, runs once when the class is defined. It has full access to the class's private names.
let readVersion; // will be assigned inside the class
class Config {
static #settings;
static #version;
static {
const defaults = { retries: 3, timeout: 5000 };
const overrides = { timeout: 8000 };
Config.#settings = Object.freeze({ ...defaults, ...overrides });
Config.#version = 2;
// Grant one outside function access to a private value
readVersion = () => Config.#version;
}
static get(key) {
return Config.#settings[key];
}
}
console.log(Config.get('timeout')); // 8000
console.log(Config.get('retries')); // 3
console.log(readVersion()); // 2The readVersion assignment shows a useful pattern. A function created inside the class body keeps access to the private names after it leaves. You can use this to give one trusted module-level helper, such as a test hook or a serializer, access without making the member public.
Static fields and static blocks are evaluated in source order, top to bottom. A static block that reads a static private field declared after it sees undefined, so declare fields first.
Brand checks against the class itself
The #field in obj check also works with static private names. It tells you whether a value is exactly the class that declared the field:
class Plugin {
static #registered = true;
static isPluginClass(value) {
return typeof value === 'function' && #registered in value;
}
}
class Extended extends Plugin {}
console.log(Plugin.isPluginClass(Plugin)); // true
console.log(Plugin.isPluginClass(Extended)); // false: subclasses lack it
console.log(Plugin.isPluginClass({})); // falseThe false for Extended follows from the rule above. Static private fields belong only to the declaring constructor. If you want to recognize subclasses too, check the prototype chain with value === Plugin || value.prototype instanceof Plugin.
Each class evaluation gets fresh private names
Private names are created when a class definition is evaluated. A factory function that returns a new class on every call produces separate private names and separate static state each time:
function makeCounterClass() {
return class {
static #n = 0;
static next() { return ++this.#n; }
static owns(c) { return #n in c; }
};
}
const A = makeCounterClass();
const B = makeCounterClass();
A.next(); A.next();
console.log(B.next()); // 1: B's state is independent
console.log(A.owns(B)); // false: different #nIn an anonymous class expression you have no name to write in place of this, which is why this example uses this.#n. That is safe only while nobody subclasses the returned class. Give the class expression a name, as in return class Counter { ... }, and then use Counter.#n inside it.
Public static vs static private at a glance
| Behavior | Public static | Static private |
|---|---|---|
| Visible to `Object.keys` / reflection | Yes | No |
| Readable outside the class body | Yes | No (SyntaxError) |
| Inherited by subclasses through the prototype chain | Yes | No |
| Safe to access via `this` in static methods | Yes | Only if never subclassed |
| Usable with `#name in value` | No | Yes |
Exercise
A class Shape has static #created = 0; and a static method static track() { this.#created++; }. The Circle extends Shape constructor calls Circle.track(). What happens, and what is the smallest fix that keeps a single shared counter?
Show answer
Circle.track() runs with this === Circle. Circle has no #created of its own, and private lookups do not follow the prototype chain, so the call throws a TypeError. The fix is to write Shape.#created++ inside track(), so that every call updates the one field on Shape.
Exercise
Write a class RateLimiter with a static private field holding the maximum calls per minute (default 60), a static private method that checks a number is a positive integer, and a public static getter and setter named limit that uses the method to reject invalid values with a RangeError.
Show answer
class RateLimiter { static #limit = 60; static #isPositiveInt(n) { return Number.isInteger(n) && n > 0; } static get limit() { return RateLimiter.#limit; } static set limit(n) { if (!RateLimiter.#isPositiveInt(n)) throw new RangeError('limit must be a positive integer'); RateLimiter.#limit = n; } } Then RateLimiter.limit = 100 works, while RateLimiter.limit = -5 throws a RangeError.
Exercise
Why does #registered in Extended return false when Extended extends Plugin and only Plugin declares static #registered?
Show answer
A static private field is installed only on the constructor whose class body declares it. Extended inherits public statics through its prototype link to Plugin, but it never receives its own #registered, and in checks for private names do not walk the prototype chain.