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

What happens when this runs in plain JavaScript?

class Base {
  constructor(n) { this.n = n; }
}
class Child extends Base {
  constructor(n) {
    this.tag = "x";
    super(n);
  }
}
new Child(1);
A ReferenceError, because this is used before super() is called

It throws a ReferenceError. In a derived class, super() is what creates this. So you cannot touch this until super() has run. TypeScript also reports this at compile time.

"It works, and the object has
tag and n" is tempting because the order looks harmless. But the object does not exist yet when this.tag is set. Fix: call super(n) first.