Static members and factories

A static method belongs to the class rather than to an instance, and a static field is a place for data that the class itself owns. Both are ordinary properties of the constructor function, which is why a subclass inherits them along the class chain, and why this inside a static method is the class the call went through.

This lesson writes a counter on a class, shows a subclass that replaces one static field and inherits the method that reads it, and then uses the last tool of this part: a function that returns a class. That function is how one implementation becomes several classes with their own hidden state.

Static methods and fields

A static method is called on the class, and a static field is read there too: Id.create("task") and Id.next are properties of the constructor object. The field is one number for the whole class, so every call sees the value the call before left. An instance is not involved and owns nothing of it.

The file static.mjs:

class Id { static next = 1; static create(prefix) { const id = `${prefix}-${Id.next}`; Id.next += 1; return id; } } console.log(Id.create('task')); console.log(Id.create('task')); console.log(Id.create('note')); console.log('the counter is on the class:', Id.next); console.log('an instance has no such field:', Object.hasOwn(new Id(), 'next'));

node static.mjs

task-1
task-2
note-3
the counter is on the class: 4
an instance has no such field: false

Three identifiers with three different numbers, because the counter lived on the class between calls. The last line asks an instance whether it owns the field and gets a no, which is the difference between a static member and a field. A static counter is the standard use of the feature: an id generator needs one state for the class and none per object.

Static members are inherited

The parent of a class is also its prototype, so a static method is inherited and this inside it is the class that received the call. That is what makes Model.describe() and User.describe() answer differently from one function: the method reads this.table, and the value of that field belongs to the class the call names.

The file inherited.mjs:

class Model { static table = 'models'; static describe() { return `the table is ${this.table}`; } } class User extends Model { static table = 'users'; } class Guest extends Model {} console.log(Model.describe()); console.log(User.describe()); console.log(Guest.describe()); console.log('a subclass may own the field:', Object.hasOwn(User, 'table')); console.log('and one without it borrows the parent:', Object.hasOwn(Guest, 'table')); console.log('the classes are chained:', Object.getPrototypeOf(User) === Model);

node inherited.mjs

the table is models
the table is users
the table is models
a subclass may own the field: true
and one without it borrows the parent: false
the classes are chained: true

Three calls, two answers, and the method was written once. The class with its own field answered with it, and the class without one borrowed the value from its parent. The last line is the link that carries all of this: the prototype of a class is its parent class, which is a chain separate from the one instances use.

A factory returns a class

A class expression can be returned from a function, and the closure of that function is then the private state of the class. The factory below returns a class whose field starts at the value the caller gave, so two calls make two classes with different defaults and no shared variable. This is the pattern to reach for when classes differ only in a constant.

The file factory.mjs:

function makeCounter(start) { return class Counter { #value = start; bump() { this.#value += 1; return this.#value; } get value() { return this.#value; } }; } const FromZero = makeCounter(0); const FromTen = makeCounter(10); const a = new FromZero(); a.bump(); a.bump(); const b = new FromTen(); b.bump(); console.log('from zero:', a.value); console.log('from ten:', b.value); console.log('the classes are different:', FromZero !== FromTen); console.log('each keeps its own start:', new FromZero().value, new FromTen().value); console.log('the class name is the same:', new FromZero().constructor.name);

node factory.mjs

from zero: 2
from ten: 11
the classes are different: true
each keeps its own start: 0 10
the class name is the same: Counter

Two counters with two starting values, and one implementation. The private field reads the parameter of the factory, which is why the class needs no constructor parameter for it. The last two lines show that the two classes are different objects with the same name, which is the expected result of one class expression evaluated twice.

One factory, two classes

A factory can also set the static fields of the class it returns, which gives each class a constant of its own. The name of the class is written once in the factory rather than in every class, so the objects report the name of the class expression and the static field carries the label the caller chose.

The file factory_static.mjs:

function labelled(label) { return class Labelled { static kind = label; constructor(value) { this.value = value; } describe() { return `${label}: ${this.value}`; } }; } const Round = labelled('round'); const Square = labelled('square'); console.log(new Round(1).describe()); console.log(new Square(2).describe()); console.log('each class has its own static field:', Round.kind, Square.kind); console.log('the instances are of different classes:', new Round(1) instanceof Square); console.log('the shared name is the one written once:', Round.name);

node factory_static.mjs

round: 1
square: 2
each class has its own static field: round square
the instances are of different classes: false
the shared name is the one written once: Labelled

The two classes answered with their own labels and refused to be instances of one another, which is the point of a class rather than a plain object. The shared name is a small cost of the pattern: a stack trace shows Labelled for both, so a factory of classes deserves a name that says what the family is. A static method is the alternative when the classes have behaviour in common, and inheritance the one when they are variations of one type.

Exercises

  1. Reset Id.next in static.mjs to 100 and create one more id. Which number comes back, and why is a static field the right place for it?
  2. Add a static method to Model in inherited.mjs that returns the length of the table name and call it on User. Which field does it read?
  3. Call the factory of factory.mjs with a negative start and print the counter after three calls. Which part of the class had to change?
  4. Write a static factory method Counter.fromTen() that returns a new instance and compare it with the class factory. Which of the two can be extended?
  5. Give the class in factory_static.mjs a static method that reports this.kind and call it on both classes. What does each answer?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How is a static method called?

    Answer

    On the class: Id.create(...)

    A static member belongs to the constructor object rather than to the instances.

  2. What is a static field good for?

    Answer

    State that the whole class shares, such as a counter

    One value per class is exactly what an id counter or a registry needs.

  3. What is this inside a static method?

    Answer

    The class the call went through

    A static method is called on a class, so the receiver is that class, subclass included.

  4. What does a factory that returns a class give that a plain class does not?

    Answer

    Each call can build a class with its own captured constants

    The closure of the factory holds the values the classes are built with.

  5. What does this program print? class Id { static next = 1; static create() { return Id.next++; } } console.log(Id.create(), Id.create());

    Answer

    1 2

    Both calls read the same static field, and the postfix increment returns the old value.

  6. What does this program print? class Id { static next = 5; } const a = new Id(); console.log(Id.next, Object.hasOwn(a, "next"));

    Answer

    5 false

    The field lives on the class, so the instance does not own it.

  7. What does this program print? class A { static table = "a"; static show() { return this.table; } } class B extends A { static table = "b"; } console.log(A.show(), B.show());

    Answer

    a b

    This is the class that received the call, so the inherited method reads the field of that class.

  8. What does this program print? function make(n) { return class Box { value = n; }; } const A = make(1); const B = make(2); console.log(new A().value, new B().value);

    Answer

    1 2

    Each class was built by a separate call, and the field initialiser reads that call of the factory.

  9. What does this program print? class A { static count = 0; constructor() { A.count += 1; } } new A(); new A(); console.log(A.count);

    Answer

    2

    Each constructor call adds to the one field that belongs to the class.

  10. What happens when this module runs? class A { static go() { return this.name; } } const go = A.go; go();

    Answer

    It throws a TypeError, because this is undefined in the detached call

    The call has no receiver, and a class body is strict code, so this is undefined and the read of name throws.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev