CodePark/ questions / Classes, constructors & fields
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Classes, constructors & fields

What does this print?

class Base {
  constructor() { this.init(); }
  init() {}
}
class Repo extends Base {
  items = [];
  init() { console.log(this.items); }
}
new Repo();
undefined

It prints undefined. A subclass's fields are created only after super() returns. Here the base constructor calls this.init() first. Method lookup still finds Repo.init, because this is already a Repo. But items does not exist yet.

"
[]" is the tempting answer. It would be true only if fields were set before the base constructor ran. The lesson: never call overridable methods from a constructor.