javascriptinheritanceconstructorproperties

Inherited javascript property not set during constructor


I have two Javascript classes, one extends the other.

The base class has a property, which is overridden by the other class.

When constructing the subclass, the property appears to be set as per the superclass.

I tried searching for this, but did not find any useful results - possibly I don't know the correct search terms.

Example:

class A {
  id = "A";
  constructor() {
    this.show();
  }

  show() {
    console.log(this.id);
  }
}
class B extends A {
  id = "B";
}

o = new B();
o.show();

Since I'm constructing a "B", I expected it to print "B" and "B", but actually it prints "A" and "B".

How do I get "B" in the superclass constructor?


Solution

  • This is due to the order that all the properties are added and initialized. It starts with the base class, working out to the final subclass.

    When you create a B, it first creates an A, which does this.id = 'A' and then calls the A constructor. This calls this.show(), which logs A.

    Then it finishes contructing the B part of the object, which does this.id = "B". Now when you call o.show(), you get the B` output.

    You generally have to be careful about how you operate on the object during construction, because it's still in an intermediate state.