Is there any way this is possible in ES6 -- or is there a nice solution if it isn't (as seems likely):
class Parent {
constructor() {
console.log(this.name);
}
}
class Child extends Parent {
name = "Child Name";
}
const c = new Child();
// Should console.log "Child Name";
(Coming from Python, where it totally works!)
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:
super(...) to execute parent constructorIf 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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With