The reasoning behind this occurrence is due to the fact that the super()
method is the first one invoked when you create a new instance of B
by calling new B('text')
. When super()
is called, it immediately triggers this.init()
. Since this
refers to an object of type B
, not A
, it attempts to execute console.log(this.text)
instead of console.log('text')
. However, at the point of this operation, this.text
has not yet been assigned a value as it happens after the call to super
.
This underscores the importance of avoiding performing tasks within the constructor. Your object is not fully functional until the constructor has completed its execution.
To address this issue, it is recommended to remove the init()
call from the parent's constructor and invoke it separately like this:
class A {
public init() {
console.log('a')
}
}
class B extends A {
constructor(public text: string) {
super(); // no longer necessary since the parent class has no constructor.
}
public init() {
console.log(this.text)
}
}
const b = new B('text');
// Object is now ready for use.
b.init();