Class instance fields are undefined when assigned from parent class constructor
07:21 26 Oct 2020

I am trying to understand the dynamics of why the following solution doesn't work in the case where a class field is assigned from parent's constructor:

class B{
  constructor(val){
        this.a = val;
    }
}

class A extends B{
  a;
  constructor(val){
    super(val);
  }
}

With the above calling new A(1) will return an instance whereas A.a is undefined.

If assignment is done via a named function rather than super constructor the implementation will work:

class B{
  assignMe(val){
        this.a = val;
    }
}

class A extends B{
  a;
  constructor(val){
    super(null);
    super.assignMe(val);
  }
}

This correctly sets A.a = 1.

Here you have a more complex implementation which represents my real-world use scenario.

Why can't I achieve this by using constructor?

javascript oop ecmascript-6 subclass class-fields