Sub topic 8
Static Methods, Static Fields, and Static Blocks
This chapter assumes you already know how to write constructors, instance methods, public instance fields, and getters. It also assumes you know that a class is a function whose methods live on prototype. Private fields get a full chapter later. Here they appear only where they interact with static members.
A static member belongs to the class itself, not to its instances. You reach it through the class name (Temperature.compare), never through an object created with new. Static members suit work that relates to the type as a whole: factory functions, comparators, counters, caches, and configuration that every instance shares.
Static Methods
Put the static keyword before a method definition to make it static. The method becomes a property of the constructor function, not of prototype.
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
static fromFahrenheit(f) {
return new this((f - 32) * 5 / 9);
}
static compare(a, b) {
return a.celsius - b.celsius;
}
}
const temps = [
new Temperature(30),
Temperature.fromFahrenheit(32),
new Temperature(15),
];
temps.sort(Temperature.compare);
console.log(temps.map((t) => t.celsius)); // [0, 15, 30]
console.log(Object.hasOwn(Temperature, 'compare')); // true
console.log(Object.hasOwn(Temperature.prototype, 'compare')); // false
console.log(typeof new Temperature(1).compare); // "undefined"Two common uses show up in this example:
- Factory methods such as
fromFahrenheitbuild instances from other inputs. Constructors can't be overloaded, so named factories are the usual way to offer several ways to create an object. - Utility functions such as
comparework on instances without belonging to any single one.
What `this` means in a static method
Inside a static method, this is whatever comes before the dot when the method is called. Usually that is the class. fromFahrenheit uses new this(...) and not new Temperature(...). That choice matters once subclasses exist:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
static fromFahrenheit(f) {
return new this((f - 32) * 5 / 9);
}
}
class LabTemperature extends Temperature {
describe() {
return `${this.celsius.toFixed(2)} °C (lab)`;
}
}
const t = LabTemperature.fromFahrenheit(100);
console.log(t instanceof LabTemperature); // true
console.log(t.describe()); // "37.78 °C (lab)"If the factory had used new Temperature(...), it would return the parent type, and the call to describe would fail.
Static Fields
Static fields declare data on the class itself. Each initializer runs once, when the class is defined. It does not run again for each instance.
class IdGenerator {
static prefix = 'id-';
static next = 1;
static sample = `${this.prefix}${this.next}`;
static create() {
return `${this.prefix}${this.next++}`;
}
}
console.log(IdGenerator.sample); // "id-1"
console.log(IdGenerator.create()); // "id-1"
console.log(IdGenerator.create()); // "id-2"Inside a static field initializer, this is the class. Initializers run top to bottom, so sample can read prefix and next because both were declared above it. If you reorder them, sample becomes "undefinedundefined". The class name is already bound while static initializers run, so IdGenerator.prefix would also work there.
An instance can still reach static data through its constructor property, which points back to the class:
class Widget {
static defaultColor = 'blue';
constructor() {
this.color = this.constructor.defaultColor;
}
}
class RedWidget extends Widget {
static defaultColor = 'red';
}
console.log(new Widget().color); // "blue"
console.log(new RedWidget().color); // "red"this.constructor resolves to the actual class, so a subclass can override the default. Writing Widget.defaultColor would lock every subclass to "blue".
How Statics Are Inherited
When you write class Child extends Base, JavaScript sets up two prototype links. Child.prototype inherits from Base.prototype, which gives you instance inheritance. Child itself inherits from Base, which gives you static inheritance.
Because of the static chain, Child.create() finds Base.create. The chain also causes a common bug with mutable static fields:
class Base {
static count = 0;
static increment() {
this.count++;
}
}
class Child extends Base {}
Child.increment();
console.log(Base.count, Child.count); // 0 1
console.log(Object.hasOwn(Child, 'count')); // truethis.count++ reads count through the chain (getting 0 from Base) and then writes 1 as a new own property on Child. From then on, Child.count shadows Base.count, and the two counters drift apart. If you want one shared counter, write Base.count++. If you want a separate counter per class, keep this.count++ but declare static count = 0 in each subclass so the behavior is explicit.
Static Initialization Blocks
Some static setup takes more than one expression: a loop, a try/catch, or several fields that depend on one computed value. A static block, written static { ... }, holds that kind of code. It runs once, during class definition, in source order with the static field initializers around it.
class Settings {
static values;
static source;
static {
const raw = '{"theme":"dark","fontSize":14}';
try {
this.values = JSON.parse(raw);
this.source = 'parsed';
} catch {
this.values = { theme: 'light', fontSize: 12 };
this.source = 'fallback';
}
}
}
console.log(Settings.values.theme, Settings.source); // "dark" "parsed"Static blocks follow these rules:
thisis the class.- Variables declared inside, including
var, are local to the block. return,await, andargumentsare not allowed. A block can't be async.- A class can have several static blocks. They run in the order they appear.
- If a block throws, the class definition throws, and the class binding is never initialized.
Granting private access from a static block
Code inside a static block is part of the class body, so it can read private names. You can use this to give one trusted function outside the class access to private state:
let readBalance;
class Account {
#balance;
constructor(initial) {
this.#balance = initial;
}
static {
readBalance = (account) => account.#balance;
}
}
console.log(readBalance(new Account(50))); // 50The function works much like a "friend" function in C++. Only code you choose gets the accessor.
Gotcha: Private Static Members and Subclasses
You can make static members private with static #name. Private names don't travel up the prototype chain, though. A private static field exists only on the class that declared it, so this.#field fails when this is a subclass:
class Registry {
static #items = [];
static add(item) {
this.#items.push(item);
return this.#items.length;
}
}
class SubRegistry extends Registry {}
console.log(Registry.add('a')); // 1
SubRegistry.add('b'); // TypeError: cannot read private member #itemsThe fix is to name the declaring class directly: Registry.#items.push(item). When a static method touches private static state, refer to the class by name, not by this.
Choosing Where Code Belongs
| Need | Good fit | Reason |
|---|---|---|
| Behavior that reads or changes one object's state | Instance method | It needs `this` to be the instance |
| Alternate way to construct instances | Static factory using `new this()` | Keeps creation logic with the type and supports subclasses |
| Helper tied to the type, such as a comparator or parser | Static method | Callers can find it through the class |
| Helper with no tie to the type | Plain module function | Exports tree-shake better and avoid `this` problems |
| Shared configuration or a cache | Static field (private if internal) | Created once, shared by everyone |
| Setup that needs statements or a `try` | Static block | Field initializers only accept a single expression |
Exercise
A Shape class declares static created = 0; and its constructor runs this.constructor.created++. After new Shape(); new Circle(); new Circle();, where class Circle extends Shape {}, what are Shape.created and Circle.created, and why?
Show answer
Shape.created is 1 and Circle.created is 2. For the Shape instance, this.constructor is Shape, so Shape.created goes from 0 to 1. For the first Circle, this.constructor is Circle. Reading Circle.created falls back through the static prototype chain and finds Shape.created, which is 1. The write then creates an own property Circle.created = 2. That shadows the parent value, so you would expect the second Circle to make it 3. Check the order again, though: the first Circle read 1 and wrote 2, and the second Circle reads its own 2 and writes 3. The correct answer is therefore Shape.created = 1 and Circle.created = 3. Circle's counter started from Shape's value, not from 0, which is exactly the shadowing bug this chapter describes.
Exercise
Rewrite this method so that it works when called on a subclass: class Cache { static #store = new Map(); static get(key) { return this.#store.get(key); } }.
Show answer
Refer to the declaring class instead of this: static get(key) { return Cache.#store.get(key); }. The private static field #store exists only on Cache, so this.#store throws a TypeError when this is a subclass.
Exercise
Why does const f = Temperature.fromFahrenheit; f(212); throw, and what are two ways to fix it?
Show answer
fromFahrenheit calls new this(...). Detaching the method means this is undefined in strict mode, so new undefined(...) throws a TypeError. You can fix it with Temperature.fromFahrenheit.bind(Temperature) or with a wrapper, (f) => Temperature.fromFahrenheit(f).