Sub topic 8
Static Methods, Static Fields, and Static Blocks
This chapter assumes you can write a class with a constructor, instance methods, and public fields, and that you know methods live on ClassName.prototype. A static member belongs to the class itself, not to its instances. Use one for data or behavior that relates to the class as a whole: factory functions, counters, shared configuration, or helpers that don't need a particular instance.
Static Methods
Put the static keyword before a method to define it on the class (the constructor function). You call it on the class, never on an instance.
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
static fromFahrenheit(f) {
return new this((f - 32) * 5 / 9);
}
}
const t = Temperature.fromFahrenheit(212);
console.log(t.celsius); // 100
console.log(typeof t.fromFahrenheit); // "undefined"Inside a static method, this is the class the method was called on. Writing new this(...) rather than new Temperature(...) means a subclass calling the inherited factory gets an instance of the subclass.
Static Fields
A static field is a property on the class, created once when the class is defined.
class Ticket {
static nextId = 1;
constructor() {
this.id = Ticket.nextId++;
}
}
new Ticket();
const second = new Ticket();
console.log(second.id); // 2
console.log(Ticket.nextId); // 3Instances can't see static members through this. Inside an instance method or the constructor, use the class name, or this.constructor if subclasses should be able to override the value.
Static Initialization Blocks
When static setup needs more than one expression, such as loops, try/catch, or derived values, use a static { } block. It runs once, in order with the static field initializers, when the class is evaluated. Inside the block, this refers to the class.
class Config {
static defaults;
static {
Config.defaults = Object.freeze({ retries: 3, timeoutMs: 1000 });
}
}
console.log(Config.defaults.retries); // 3Statics and Inheritance
Subclasses inherit static members, because the subclass constructor's prototype is the parent class. This produces a common mistake with counters:
class Base {
static count = 0;
static create() {
this.count++;
return new this();
}
}
class Child extends Base {}
Child.create();
console.log(Base.count); // 0
console.log(Child.count); // 1this.count++ reads the inherited Base.count and then writes a new own property onto Child. From that point on, the two counters are separate. If you want one shared total, write Base.count++ explicitly.
| Common error | Fix |
|---|---|
| Calling `instance.staticMethod()` | Call `ClassName.staticMethod()` |
| Reading `this.staticField` in an instance method | Use `ClassName.field` or `this.constructor.field` |
| Expecting `this.x++` in a static method to update the parent | Write to the parent class by name |
Exercise
Add a static method Ticket.reset() that sets the next id back to 1. Then explain why new Ticket().reset is undefined.
Show answer
Add static reset() { Ticket.nextId = 1; } to the class body. Static methods are defined on the Ticket constructor itself, not on Ticket.prototype, so instances don't inherit them through their prototype chain.
Exercise
In the Base/Child example, what does Base.count print if you call Base.create() twice after Child.create()?
Show answer
2. Child already has its own count property, so Base.create() increments only Base.count, which goes from 0 to 2.