Sub topic 8
Static Getters and Setters
This chapter assumes you know how class getters and setters work on instances, how extends links classes, and how property descriptors describe accessor properties. Here the same get and set syntax is moved from instances to the class itself.
What `static` changes
A static accessor is defined on the constructor function, not on prototype. You read and write it as ClassName.prop. Instances do not see it, because their prototype chain runs through ClassName.prototype, not through ClassName.
Static accessors suit state that belongs to the whole class: a shared configuration value, a registry size, or a computed summary of class-level data.
const LEVELS = ['debug', 'info', 'warn', 'error'];
let currentLevel = 'info';
class Logger {
static get level() {
return currentLevel;
}
static set level(value) {
if (!LEVELS.includes(value)) {
throw new RangeError(`Unknown level: ${value}`);
}
currentLevel = value;
}
static get levels() {
return [...LEVELS]; // a copy, so callers cannot mutate the list
}
log(level, message) {
if (LEVELS.indexOf(level) >= LEVELS.indexOf(Logger.level)) {
console.log(`[${level}] ${message}`);
}
}
}
Logger.level = 'warn';
const logger = new Logger();
logger.log('info', 'hidden'); // prints nothing
logger.log('error', 'shown'); // [error] shown
console.log(logger.level); // undefined: instances don't see static members
console.log(Logger.levels); // ['debug', 'info', 'warn', 'error']
try {
Logger.level = 'verbose';
} catch (err) {
console.log(err.message); // Unknown level: verbose
}
const desc = Object.getOwnPropertyDescriptor(Logger, 'level');
console.log(typeof desc.get, typeof desc.set, desc.enumerable); // function function falseThe descriptor shows that level is an ordinary accessor property that lives on Logger. Class accessors, static or not, are non-enumerable. The stored value here sits in a module-scoped variable. The next chapter replaces that variable with a static private field.
Where static accessors live
`this` inside a static accessor
Inside a static accessor, this is the class the property was accessed on. A subclass's constructor inherits from its parent's constructor, so static accessors are inherited, and this refers to the subclass when it is accessed through the subclass.
class Shape {
static get kind() {
return this.name.toLowerCase();
}
}
class Circle extends Shape {}
console.log(Shape.kind); // 'shape'
console.log(Circle.kind); // 'circle'
console.log(Object.getPrototypeOf(Circle) === Shape); // trueCommon error: static setters writing through `this`
The dynamic this causes a quiet bug when a static setter stores state on this:
class Base {
static _total = 0;
static get total() { return this._total; }
static set total(v) { this._total = v; }
}
class Sub extends Base {}
Sub.total = 5;
console.log(Base.total); // 0
console.log(Sub.total); // 5
console.log(Object.hasOwn(Sub, '_total')); // true: a new property on Sub shadows Base._totalThe setter runs with this === Sub, so the assignment creates an own _total on Sub. The shared counter has split in two.
| Intent | Write in the accessor |
|---|---|
| One value shared by the whole hierarchy | `Base._total` (name the class explicitly) |
| A separate value per subclass | `this._total`, on purpose, and document it |
When to reach for a static accessor
- Use one when reading or writing class-level state needs validation, a copy, or a computed result.
- Use a plain static field when the value is a constant or needs no checks.
- Use a static method when the operation takes arguments or does visible work. Assignment syntax should feel like setting a value, not like running a job.
Exercise
Given class A { static get id() { return this.name; } } and class B extends A {}, what do A.id, B.id, and new B().id return, and why?
Show answer
A.id returns 'A' and B.id returns 'B', because static accessors are inherited through the constructor prototype chain and this is the class used in the access. new B().id is undefined, because instances inherit from B.prototype, which has no id property.
Exercise
Rewrite the Base class so that Sub.total = 5 updates one counter shared by Base and Sub.
Show answer
Change the accessors to use the class name: static get total() { return Base._total; } and static set total(v) { Base._total = v; }. After that, Sub.total = 5 sets Base._total, and both Base.total and Sub.total return 5.