This is my task
- Implement a Child class that extends the Parent.
- Add a constructor to the Child class can calls super().
- Implement a new function addNewAbilities(newAbility) in the Child class where the new ability will be added to the Parent’s #abilities array.
I have tried adding into the creating a new function here but it’s not working. Not sure if i’m creating the function correctly. Could anyone help to see?
class Parent {
abilities = []
constructor(){
this.abilities.push("Parenting");
this.abilities.push("Role modeling");
}
showAbilities(){
console.log("These are the abilities:")
for(const a of this.abilities){
console.log(a);
}
}
}
const p = new Parent();
p.showAbilities(); // Observe that this function prints "Parenting" and "Role modeling".
// Task 1: Add code here
class Child extends Parent {
addNewAbility = []
super() {
this.addNewAbility.push("Parenting");
}
}
const c = new Child();
c.addNewAbility("Dancing");
c.showAbilities(); // This function should print "Parenting", "Role modeling" and "Dancing".
2
Answers
You need to call
super
within the constructor of the child class:When you call
super
within the constructor, it calls the parent’s constructor form the child class.Here’s a link to a good explanation for how
super
works.In the
Child
class, you don’t need to define ‘addNewAbility’ as an array. Instead, you should use the abilities property inherited from theParent
class to store more abilities.Also, your
Child
class is missing theconstructor
function. The constructor should use thesuper()
keyword to call the constructor of the parent classParent
.Here your revised code:
Cheers!