Skip to content
jshacks.dev
Fundamentals

Static Class Members and Static Initialization Blocks

Static members belong to the class, not its instances, and subclasses inherit them. See this in static methods, shared state and static blocks.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, TypeScript and Vite logos.

Some behavior belongs to the class as a whole and not to any single instance: a factory that builds instances in a certain way, a counter of how many were made, a registry, a constant. static puts that behavior on the class object itself. The feature is easy to use and has three details that matter in practice, which are what this means inside a static method, how static state is shared with subclasses, and when the code in a static block runs relative to the rest of the class. This post covers each with output from Node.js 24 as an ES module, and finishes with the patterns where static members are the right tool and where a module-level function is simpler. The class model underneath is in the post on classes being functions, and the privacy side is in the post on private fields.

Static methods and fields

A static member is declared with the static keyword and read from the class.

JavaScript
class Temperature {
  static ABSOLUTE_ZERO = -273.15;

  static fromFahrenheit(f) {
    return new Temperature(((f - 32) * 5) / 9);
  }

  constructor(celsius) {
    this.celsius = celsius;
  }

  get kelvin() {
    return this.celsius - Temperature.ABSOLUTE_ZERO;
  }
}

const boiling = Temperature.fromFahrenheit(212);

console.log(boiling.celsius);
console.log(Temperature.ABSOLUTE_ZERO);
console.log(boiling.kelvin);
console.log(typeof boiling.fromFahrenheit, boiling.ABSOLUTE_ZERO);
console.log(Object.getOwnPropertyNames(Temperature));
Text
100
-273.15
373.15
undefined undefined
[ 'length', 'name', 'prototype', 'fromFahrenheit', 'ABSOLUTE_ZERO' ]

The factory and the constant are properties of the class. The instance does not have them: boiling.fromFahrenheit is undefined, and the names are listed on the constructor, not on the prototype. A static factory with a descriptive name is often clearer than a constructor with several optional modes, since Temperature.fromFahrenheit(212) says what it does.

this in a static method

Inside a static method, this is whatever the method was called on. For an inherited static, that is the subclass, not the class that defined the method.

JavaScript
class Model {
  static table = "models";

  static create(data) {
    return Object.assign(new this(), data);
  }

  static describe() {
    return `${this.name} uses ${this.table}`;
  }
}

class User extends Model {
  static table = "users";
}

class Post extends Model {}

const user = User.create({ name: "Ada" });

console.log(user instanceof User);
console.log(User.describe());
console.log(Post.describe());
console.log(Model.describe());
console.log(Object.getPrototypeOf(User) === Model);
Text
true
User uses users
Post uses models
Model uses models
true

User.create made a User, because new this() used the class it was called on. User.describe() saw its own table and name, while Post, which declared no table, found the parent's through the inheritance link. This pattern is the basis of active-record style models and of any base class that builds its subclasses' instances. Writing new Model() in the factory instead would have returned a plain Model for every subclass, which is the usual bug.

Shared mutable static state

A static field is a property on the constructor, and a subclass reads it through the constructor's prototype link. If the value is an array or object, the subclass gets the same one, not a copy.

JavaScript
class Registry {
  static entries = [];

  static register(name) {
    this.entries.push(name);
  }
}

class PluginRegistry extends Registry {}

Registry.register("core");
PluginRegistry.register("plugin-a");

console.log(Registry.entries);
console.log(PluginRegistry.entries === Registry.entries);

class SeparateRegistry extends Registry {
  static entries = [];
}

SeparateRegistry.register("isolated");

console.log(Registry.entries);
console.log(SeparateRegistry.entries);
console.log(Object.hasOwn(PluginRegistry, "entries"), Object.hasOwn(SeparateRegistry, "entries"));
Text
[ 'core', 'plugin-a' ]
true
[ 'core', 'plugin-a' ]
[ 'isolated' ]
false true

Registering through the subclass changed the parent's array, since both names reach one array. Redeclaring the field in the subclass gave it a separate one. A primitive static behaves differently, because assigning through the subclass creates an own property on it: Sub.count += 1 reads the inherited value and writes an own one. When each subclass needs its own state, either redeclare the field or key the data by this, using a Map from class to value.

JavaScript
class Counter {
  static #counts = new Map();

  static increment() {
    const next = (Counter.#counts.get(this) ?? 0) + 1;
    Counter.#counts.set(this, next);
    return next;
  }
}

class A extends Counter {}
class B extends Counter {}

console.log(A.increment(), A.increment(), B.increment(), Counter.increment());
Text
1 2 1 1

The map keyed by this gave each class its own counter without any redeclaration. It uses a private static, so the map is hidden from callers.

Static initialization blocks

A static { } block runs once, when the class is defined, and can contain any statements. It is for setup that does not fit in a single field expression.

JavaScript
const log = [];

class Config {
  static defaults = (log.push("field defaults"), { retries: 3 });

  static {
    log.push("block one");
    Config.ready = Object.keys(Config.defaults).length > 0;
  }

  static timeout = (log.push("field timeout"), 5000);

  static {
    log.push("block two sees timeout " + Config.timeout);
  }
}

log.push("after class");

console.log(log);
console.log(Config.ready);
Text
[
  'field defaults',
  'block one',
  'field timeout',
  'block two sees timeout 5000',
  'after class'
]
true

Fields and blocks run in source order, interleaved, and all of them run before the code after the class. The second block could read timeout because that field had already been initialized, and the first block ran after defaults and before timeout. Inside the block, this is the class, so this.ready = true also works.

A block can read private static members and handle errors with try and catch, which a field initializer cannot do cleanly.

JavaScript
class Environment {
  static #raw = { MODE: "production", LIMIT: "x" };
  static mode;
  static limit;

  static {
    this.mode = Environment.#raw.MODE ?? "development";
    try {
      const parsed = Number(Environment.#raw.LIMIT);
      if (Number.isNaN(parsed)) throw new RangeError("bad limit");
      this.limit = parsed;
    } catch {
      this.limit = 100;
    }
  }
}

console.log(Environment.mode, Environment.limit);
Text
production 100

The block parsed a value that failed validation and fell back to a default, all at definition time. Before static blocks, this setup lived in an immediately invoked function after the class, which could not see private members.

Static members and instances

Because statics are not on the prototype, an instance cannot call them directly. Inside an instance method, reach them through the class or through this.constructor.

JavaScript
class Widget {
  static count = 0;

  constructor() {
    Widget.count += 1;
    this.id = this.constructor.count;
  }

  static reset() {
    this.count = 0;
  }
}

new Widget();
new Widget();
const third = new Widget();

console.log(third.id, Widget.count);
console.log(third.count);

Widget.reset();
console.log(Widget.count);
Text
3 3
undefined
0

The counter is class-level state and is incremented in the constructor. third.count is undefined, since an instance does not inherit statics. Referencing Widget.count by name is clear, and this.constructor.count follows subclasses, which is occasionally what you want and often a surprise.

Constants and namespacing

The most common static field is a constant that belongs with a class: a limit, a default, an enumeration of allowed values. Putting it on the class keeps it next to the code that uses it, and Object.freeze() stops accidental writes. For an enumeration, a frozen static object works well, and each value is a string so that it survives serialization.

JavaScript
class Order {
  static STATUS = Object.freeze({
    OPEN: "open",
    PAID: "paid",
    SHIPPED: "shipped",
  });

  static MAX_LINES = 50;

  status = Order.STATUS.OPEN;

  pay() {
    this.status = Order.STATUS.PAID;
    return this;
  }
}

console.log(new Order().pay().status);
console.log(Object.values(Order.STATUS));
console.log(Object.isFrozen(Order.STATUS));
Text
paid
[ 'open', 'paid', 'shipped' ]
true

Callers write Order.STATUS.PAID and get autocomplete, and a typo produces undefined that a type checker would flag. Freezing is shallow and protects the object from edits, so a stray assignment in a module that imports the class cannot change the allowed values for everyone. For TypeScript projects, an as const object or a union of string literals gives the same safety at compile time.

Testing statics

Static state is the part of a class that survives from one test to the next, so tests need to reset it, and a test for a factory should check the subclass behavior and not only the base. Both fit in a few lines.

JavaScript
import { test, beforeEach } from "node:test";
import assert from "node:assert/strict";

class Widget {
  static count = 0;
  static create() {
    Widget.count += 1;
    return new this();
  }
  static reset() {
    Widget.count = 0;
  }
}

class Gadget extends Widget {}

beforeEach(() => Widget.reset());

test("the factory builds the subclass it was called on", () => {
  assert.ok(Gadget.create() instanceof Gadget);
});

test("the counter starts from zero in every test", () => {
  Widget.create();
  Widget.create();
  assert.equal(Widget.count, 2);
});

Run it with node --test on Node.js 24. Without the beforeEach reset, the second test would see the count left over from the first and fail only when run after it, which is the signature of leaked static state. If you find yourself writing reset() methods only for tests, take it as a hint that the state should be an instance field on an object you create per test, as in the post on getters and setters, which keeps its state in each instance.

Where static members stop being a good idea

Static methods that do not need the class, such as a helper that formats a number, are plain functions wearing a class name. A module-level function is simpler, easier to import and easier to tree-shake. Static mutable state is global state with a class name: it persists across tests, and it is shared by every consumer of the module. Prefer to keep state in instances, and give tests a way to reset it, as reset() does above.

Classes with only static members, used as namespaces, are better as modules. And a hierarchy that relies on this in statics can be hard to follow, so keep the factory pattern for a base class that is meant to be extended.

Static members are defined in the specification under class definition evaluation, and MDN's pages on static and static initialization blocks list the forms.

Also inPatterns
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.