Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Class field initialization order with super() in JavaScript

46 A class field is assigned after super() returns

hard

A parent constructor calls a method the child overrides, and the child also declares a class field of the same name. Work out which value survives, then get the behaviour you wanted by assigning in the constructor instead. Finally show that fields initialise top to bottom.

Stuck? Three hints, smallest first
  1. 1. A child field initialiser runs immediately after super() returns — that is, after everything the parent constructor did.
  2. 2. So a field will overwrite whatever the parent assigned to the same property name.
  3. 3. Field initialisers run in source order, and each one can read only the fields above it.

The answer

const calls = [];

class Base {
  constructor() {
    calls.push('Base constructor');
    this.setUp();                             // calls the child's override
  }
  setUp() {
    this.ready = 'base';
  }
}

class WithField extends Base {
  ready = 'field';                            // runs AFTER super() returns
  setUp() {
    calls.push('override ran');
    this.ready = 'override';
  }
}

class WithAssignment extends Base {
  constructor() {
    super();                                  // override's value is left alone
    calls.push('after super');
  }
  setUp() {
    this.ready = 'override';
  }
}

const surprising = new WithField();
const expected = new WithAssignment();

class Rate {
  constructor() { this.kobo = 25000; }
}
class Doubled extends Rate {
  twice = this.kobo * 2;                      // parent already ran, so this works
}

class Forward {
  first = 1;
  second = this.first + 1;
}
class Backward {
  second = this.first + 1;                    // first is still undefined here
  first = 1;
}

class Both {
  field = () => 'arrow';
  method() { return 'method'; }
}
const both = new Both();

console.log('call order    :', calls);
console.log('with a field  :', surprising.ready, '<- the override was overwritten');
console.log('with an assign:', expected.ready);
console.log('field reading the parent:', new Doubled().twice);
console.log('top to bottom :', new Forward().second, '| bottom to top:', new Backward().second);
console.log('own keys of Both:', Object.keys(both));

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 parent constructor did call the child override', calls.slice(0, 2), ['Base constructor', 'override ran']);
test('but the child field ran afterwards and overwrote it', surprising.ready, 'field');
test('a child with no field of that name keeps the override', expected.ready, 'override');
test('a field can read what the parent set, because super() has already returned', new Doubled().twice, 50000);
test('fields initialise in source order', new Forward().second, 2);
test('so a field cannot read one declared below it', Number.isNaN(new Backward().second), true);
test('a field is an own property of every instance; a method is not', Object.keys(both), ['field']);
test('so two instances get two different function objects for the field', new Both().field === new Both().field, false);
test('while the method is one shared function', new Both().method === both.method, true);

This is the initialise-in-the-parent trap, and it costs people an afternoon. The order is: parent constructor runs to completion, then the child's field initialisers, then the rest of the child constructor. So a child field always wins over anything the parent assigned to the same name, including a value the parent computed by calling a method the child overrode. If you need the parent's work to stand, assign in the constructor after super() instead of declaring a field — or better, do not call overridable methods from a constructor at all.

The Backward class shows the same ordering rule inside one class: field initialisers are statements that run in sequence, so reading a field declared below gives undefined, and undefined + 1 is NaN rather than an error. The last pair is a cost, not a bug: a field holding an arrow is per-instance, so a thousand instances hold a thousand functions.

Newsletter

New writing, when it lands.

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