skip to Main Content

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


  1. You need to call super within the constructor of the child class:

    class Child extends Parent {
        addNewAbility = []
        
        constructor() {
            super()
            this.addNewAbility.push("Parenting")
        }
    

    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.

    Login or Signup to reply.
  2. In the Child class, you don’t need to define ‘addNewAbility’ as an array. Instead, you should use the abilities property inherited from the Parent class to store more abilities.

    Also, your Child class is missing the constructor function. The constructor should use the super() keyword to call the constructor of the parent class Parent.

    Here your revised code:

    class Child extends Parent {
        constructor() {
            super(); 
            this.abilities.push("Childcare"); 
        }
    }
    

    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search