Skip to content

OutputNot attempted

Parent constructor calls an overridden method

class Base {
constructor() {
this.init();
}
init() {
this.type = 'base';
}
}
class Child extends Base {
name = 'child';
init() {
this.type = `child:${this.name}`;
}
}
console.log(new Child().type);

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Class fields are initialised right AFTER super() returns. Base's constructor calls the overridden init before Child's name field exists → "child:undefined". Don't call overridable methods from a constructor.