A parent's constructor is called before the child can initialize their instance data so you can't refer to a child's instance in the parent's constructor. That's just wrong OOP design (at least in Javascript). If the parent wants access to a property in the constructor, then define and initialize the property in the constructor of the parent (the child can still use it).
Parents should not depend upon children - children depend upon the parent.
So, this is flawed OOP design. You don't show the actual problem you're trying to solve so we can't really suggest what the correct design would be for the actual problem.
To review, the order of things is:
- Child constructor is called
- Child constructor calls
super(...)
to execute parent constructor
- Parent constructor initializes its instance data
- After parent constructor returns, Child constructor has an opportunity to initialize its instance data
If using ES6 class definitions, you don't get to change this sequencing to something different.
Based on your latest comment to this answer, I don't think there's really a better way, than just adding the extra lines of code to each child:
class Parent {
constructor(name) {
if (!name) {
// could also throw an exception here if not
// providing a name is a programming error and is not allowed
this.name = "Default Name";
} else {
this.name = name;
}
console.log(this.name);
}
}
class ChildA extends Parent {
constructor() {
super("ChildA Name");
}
}
class ChildB extends Parent {
constructor() {
super("ChildB Name");
}
}
const c = new ChildA();
// Should console.log "ChildA Name";