Question
In the context of this exercise, does a child class inherit their parent class’s constructor method?
Answer
Yes, a child class will inherit their parent class’s constructor()
method. As a result, by default, if you do not define a constructor()
method within the child class, then it will call the constructor of the parent class.
If you define a constructor()
method within the child class, then it will override the method of the parent, however, doing this may cause some issues, such as if the child’s constructor does not declare some property that was declared in the parent’s constructor. To prevent such issues, you can call the parent’s constructor, using super()
.
class Parent {
constructor() {
this.param = 10;
}
}
class Child extends Parent {
constructor(name) {
super();
this.name = name;
}
}
const bob = new Child("Bob");
console.log(bob.param); // 10