Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Static fields and static blocks in JavaScript

43 Static members, and a static block

fair

Build a fare table on the class itself: a static field for the base fare, a private static Map of area multipliers filled by a static block, and a static method that prices a trip. Then subclass it with a different base fare and see which one the inherited static method uses.

Stuck? Three hints, smallest first
  1. 1. static members hang off the class, not off instances, so Fare.base works and ride.base does not.
  2. 2. A static { ... } block runs once, when the class is defined, and can reach private static fields.
  3. 3. Inside a static method this is the class the call was made on, which for a subclass is the subclass.

The answer

class Fare {
  static base = 25000;                        // kobo
  static #rates = new Map();

  static {                                    // runs once, at definition time
    Fare.#rates.set('Ikeja', 1);
    Fare.#rates.set('Lekki', 2.5);
    Fare.#rates.set('Yaba', 1.5);
  }

  static price(area) {
    if (!Fare.#rates.has(area)) throw new RangeError(`no rate for ${area}`);
    return Math.round(this.base * Fare.#rates.get(area));   // this = the class called on
  }
  static rateViaThis(area) {
    return this.#rates.get(area);             // only works when this really is Fare
  }
  static get areas() {
    return [...Fare.#rates.keys()];
  }
  constructor(area) {
    this.area = area;
    this.kobo = Fare.price(area);
  }
}

class NightFare extends Fare {
  static base = 40000;                        // same table, dearer base
}

const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };

const ride = new Fare('Ikeja');
const areasKnownBeforeAnyInstance = Fare.areas;
const dayLekki = Fare.price('Lekki');
const nightIkeja = NightFare.price('Ikeja');
const unknown = attempt(() => Fare.price('Epe'));
const privateViaFare = Fare.rateViaThis('Ikeja');
const privateViaSubclass = attempt(() => NightFare.rateViaThis('Ikeja'));

console.log('areas    :', areasKnownBeforeAnyInstance);
console.log('day Lekki:', dayLekki, '| night Ikeja:', nightIkeja);
console.log('instance :', ride, '| ride.base:', ride.base);
console.log('unknown area     :', unknown);
console.log('#rates via Fare  :', privateViaFare, '| via NightFare:', privateViaSubclass);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the static block filled the table before any instance existed', areasKnownBeforeAnyInstance, ['Ikeja', 'Lekki', 'Yaba']);
test('a static method prices a trip from the static field', dayLekki, 62500);
test('a static is on the class, not on instances', [ride.base === undefined, Fare.base], [true, 25000]);
test('the instance still reached it through the class name', ride.kobo, 25000);
test('this in a static method is the class it was called on, so the subclass base wins', nightIkeja, 40000);
test('an area the table does not know throws', unknown, 'RangeError');
test('a private static is readable through this when this is the declaring class', privateViaFare, 1);
test('but the subclass has no such private field, so this.#rates throws', privateViaSubclass, 'TypeError');
test('statics are inherited by the subclass as a class, not copied', NightFare.areas, ['Ikeja', 'Lekki', 'Yaba']);

The static block exists because a static field initialiser is a single expression: anything needing several statements, or a loop, or a try, had to be done after the class body where it reads as an afterthought. The block runs once at definition, in order with the static fields, with this bound to the class, and it is the only place outside a method that can touch a private static.

Two behaviours worth separating. this.base inside a static method is late-bound, so NightFare.price silently prices at the subclass's base — usually exactly what you want, and a shock if you assumed a static was fixed at 25000. this.#rates is the opposite: private names are resolved against the declaring class, and NightFare is not it, so the same this that helpfully became the subclass now makes the lookup a TypeError. Name the class explicitly when reaching for a private static.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.