Sub topic 8
Static Getters and Setters
A static getter or setter is an accessor property on the class constructor itself. It is not on the prototype, so instances never see it directly. Static accessors are useful for class-level state such as configuration, counters, constants, and lazily built shared resources. This chapter covers where they live, how this behaves inside them, how they interact with subclasses, and the edge cases that come up in real code.
This chapter assumes you know ES2015 class syntax and extends, the basics of prototypes, and the instance getters and setters covered earlier in the tutorial.
Declaring a Static Accessor
Put static in front of get or set. The example below keeps a default unit in a module-scoped variable and uses the static setter to validate every change.
let defaultUnit = 'C';
const allowedUnits = ['C', 'F', 'K'];
class Temperature {
static get defaultUnit() {
return defaultUnit;
}
static set defaultUnit(unit) {
if (!allowedUnits.includes(unit)) {
throw new RangeError(`Unknown unit: ${unit}`);
}
defaultUnit = unit;
}
constructor(value, unit = Temperature.defaultUnit) {
this.value = value;
this.unit = unit;
}
}
Temperature.defaultUnit = 'K';
const t = new Temperature(300);
console.log(t.unit); // 'K'
console.log(t.defaultUnit); // undefined
console.log(t.constructor.defaultUnit); // 'K'
const desc = Object.getOwnPropertyDescriptor(Temperature, 'defaultUnit');
console.log(typeof desc.get, typeof desc.set); // 'function' 'function'
console.log(desc.enumerable, desc.configurable); // false true
console.log(Object.getOwnPropertyDescriptor(Temperature.prototype, 'defaultUnit')); // undefined
try {
Temperature.defaultUnit = 'Rankine';
} catch (err) {
console.log(err.message); // 'Unknown unit: Rankine'
}The descriptor check shows the key fact. defaultUnit is an own accessor property of the Temperature function object, and Temperature.prototype has nothing by that name. An instance reading t.defaultUnit walks its own prototype chain (Temperature.prototype, then Object.prototype) and finds nothing. To reach class-level state from an instance, go through the class name or this.constructor.
Like instance accessors declared in a class body, static accessors are non-enumerable and configurable.
What `this` Means Inside a Static Accessor
Inside a static getter or setter, this is the object the property was accessed on. That is usually the class. It becomes interesting with subclasses, because class B extends A sets Object.getPrototypeOf(B) to A. Static members are inherited through that constructor-to-constructor chain, and this refers to the subclass when you access the member 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); // true
console.log(Object.hasOwn(Circle, 'kind')); // falseCircle has no kind property of its own. The lookup finds the getter on Shape and calls it with this === Circle, so this.name is 'Circle'.
This behavior lets one getter produce a different answer for each subclass. It also causes the subtle bugs described in the sections below.
Static Setters and Per-Subclass State
A static setter also receives the subclass as this. If the setter writes to this.something, the write lands on whichever class was used in the assignment.
class Config {
static _level = 'info';
static get level() {
return this._level;
}
static set level(value) {
this._level = value;
}
}
class DbConfig extends Config {}
DbConfig.level = 'debug';
console.log(DbConfig.level); // 'debug'
console.log(Config.level); // 'info'
console.log(Object.hasOwn(DbConfig, '_level')); // trueDbConfig.level = 'debug' finds the inherited setter and calls it with this === DbConfig. Inside it, this._level = value assigns to DbConfig. The inherited _level on Config is a writable data property, so the assignment creates a new own property on DbConfig that shadows it. Each subclass ends up with its own setting, and the parent keeps its own.
You may want that. If the setting should be global for the whole hierarchy instead, name the class explicitly:
| Intent | Write in the setter | Effect of `DbConfig.level = 'debug'` |
|---|---|---|
| Per-subclass value | `this._level = value` | New own `_level` on `DbConfig`; `Config` unchanged |
| One shared value | `Config._level = value` | `Config._level` changes; every subclass sees it |
| Shared, fully hidden | Assign to a module-scoped variable | Same as shared, but nothing visible on the classes |
Getter-Only Static Properties
A static getter with no setter gives you a read-only, computed class property. Assigning to it fails. In strict mode the failure is a TypeError. In sloppy mode the assignment is silently ignored. Class bodies are always strict, but the code doing the assignment may not be, so the strict directive matters at the call site.
'use strict';
class Limits {
static get MAX_USERS() {
return 100;
}
}
class ProLimits extends Limits {}
try {
Limits.MAX_USERS = 5;
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
ProLimits.MAX_USERS = 5; // inherited getter-only accessor also blocks assignment
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Limits.MAX_USERS, ProLimits.MAX_USERS); // 100 100The second case catches people out. Assigning a property normally creates an own property on the target. That does not happen when the inherited property is an accessor. The accessor's setter is used, and because there is no setter, the assignment fails. To give ProLimits a different limit, declare static get MAX_USERS() on ProLimits itself, or use Object.defineProperty(ProLimits, 'MAX_USERS', { value: 500 }).
The reverse case also exists. A static setter with no getter makes reads return undefined. That is almost always a mistake, so define getters and setters in pairs.
Static Field or Static Getter?
The two look alike from the outside, Class.name in both cases, but they are different kinds of property.
| Feature | `static x = expr` | `static get x()` |
|---|---|---|
| Property kind | Data property | Accessor property |
| When `expr` runs | Once, when the class is defined | On every read |
| Enumerable | Yes, so it appears in `Object.keys(Class)` | No |
| Writable by default | Yes | Only if a setter exists |
| `this` at evaluation | The declaring class | The class it was read through |
| Can validate assignments | No | Yes, with a paired setter |
Two practical consequences follow from the table. First, Object.keys(Config) lists _level but not level, so code that copies or logs class-level settings by enumerating keys will skip your accessors. Second, a static field initializer runs once with this bound to the declaring class. A getter sees the subclass on every read. If you need a value that depends on the subclass, a field cannot do it.
Lazy, Cached Static Getters
Some class-level resources are expensive to build and may never be needed: a compiled regex table, an Intl formatter, a parsed config file. A common pattern is a static getter that builds the value on first read and then replaces itself with a plain data property.
class Money {
static get formatter() {
console.log('building formatter');
const value = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
Object.defineProperty(this, 'formatter', {
value,
writable: false,
configurable: true
});
return value;
}
}
console.log(Money.formatter.format(1234.5)); // logs 'building formatter', then '$1,234.50'
console.log(Money.formatter.format(9)); // '$9.00' with no rebuild
const desc = Object.getOwnPropertyDescriptor(Money, 'formatter');
console.log('value' in desc, desc.get); // true undefinedObject.defineProperty is needed here. A plain this.formatter = value would call the property's setter, which does not exist, and throw in strict class code. defineProperty replaces the accessor with a data property directly. Keep configurable: true so the property can be redefined later, for example in tests.
This pattern has a subclass edge case. Because this is whatever class the getter was read through, the first read through a subclass defines the cached property on the subclass. The parent stays lazy and builds a second copy when it is read later:
class BaseMoney {
static get formatter() {
console.log(`building for ${this.name}`);
const value = new Intl.NumberFormat('en-US');
Object.defineProperty(this, 'formatter', { value, configurable: true });
return value;
}
}
class EuroMoney extends BaseMoney {}
EuroMoney.formatter; // building for EuroMoney
BaseMoney.formatter; // building for BaseMoney
EuroMoney.formatter; // (cached on EuroMoney, no log)If one shared instance is the goal, define the cache on BaseMoney explicitly instead of on this. If each subclass should get its own instance (for example, each subclass overrides a static currency field), using this is correct. Make that choice deliberately.
Static Accessors Without Class Syntax
Classes are functions, so you can attach static accessors to any constructor with Object.defineProperty, as in the earlier chapter on that API:
function Legacy() {}
Object.defineProperty(Legacy, 'version', {
get() { return '1.0.0'; },
enumerable: false,
configurable: true
});
console.log(Legacy.version); // '1.0.0'The static get syntax produces the same descriptor shape. It is the clearer choice whenever you control the class body.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| `instance.x` is `undefined` | `x` is static and lives on the constructor | Use `Class.x` or `this.constructor.x` |
| Subclass assignment throws TypeError | Inherited static accessor has no setter | Override in the subclass or use `defineProperty` |
| Parent setting unchanged after `Sub.x = v` | Setter wrote to `this`, creating a property on `Sub` | Write to the parent class or a module variable |
| Accessor missing from `Object.keys(Class)` | Class accessors are non-enumerable | Read it by name or list it explicitly |
| Lazy getter runs twice | Cache was defined on a subclass via `this` | Define the cache on the base class |
Exercise
Given class A { static get id() { return this.name + '!'; } } and class B extends A {}, what do A.id, B.id, and Object.hasOwn(B, 'id') return, and why?
Show answer
A.id is 'A!' and B.id is 'B!'. Object.hasOwn(B, 'id') is false. The getter lives only on A. When you read B.id, the lookup goes up B's constructor prototype chain to A and calls the getter with this === B, so this.name is 'B'.
Exercise
A Settings class has static _theme = 'light' and a static getter/setter pair theme that reads and writes this._theme. After class Admin extends Settings {} and Admin.theme = 'dark', what is Settings.theme? Change the setter so the assignment updates the theme for the whole hierarchy.
Show answer
Settings.theme is still 'light'. The setter ran with this === Admin, so this._theme = 'dark' created an own _theme on Admin. To share one value, write static set theme(v) { Settings._theme = v; }, and read Settings._theme in the getter as well. Otherwise Admin's leftover own property, if one exists, would still shadow the shared value.
Exercise
Why does a lazy static getter that caches with this.cache = value fail, while Object.defineProperty(this, 'cache', { value }) works, when cache is the getter's own name?
Show answer
this.cache = value is an ordinary assignment. The property is an accessor with no setter, so the assignment throws a TypeError in strict class code. Object.defineProperty does not go through the setter. It replaces the accessor (which is configurable) with a data property, so later reads return the cached value directly.