Home > front end >  How do you pass an array of objects from a parent class to a child class?
How do you pass an array of objects from a parent class to a child class?

Time:12-10

ok say I have a class that takes a user input and inserts it into an object, that object is now being pushed into a new array called data (this.data).

class Player {
  constructor(size) {
    this.data = new Array(size)
  }

  getPlayerInfo() {
    
    let userName = " "
    let characteristicMap = {UserName : " " ,
                             Type     : " " , 
                             Village  : " "}
    
               

   ....



    
    this.data.push([characteristicMap])
   
   console.log(this.data)
   
  
  }
} 

if I wanted to make a child class that uses the data from the parent class's array how would I go about doing it?

class War extends Player {
    

  
  
}

CodePudding user response:

You can simply access the data from the parent class like it belongs to the child class.

class Player {
  constructor(size) {
    this.data = new Array(size)
  }

  getPlayerInfo() {
    this.data.push({id: 1, value: 101});
  }
} 

class War extends Player {
  constructor(size) { super(size) };
  showPlayerInfo() {
    console.log(this.data[2].id, this.data[2].value);
  }
}

let w = new War(2);
w.getPlayerInfo();
w.showPlayerInfo();
console.log(w.data);

CodePudding user response:

You can access all the parent's class properties and methods using the super keyword.

(MDN article about the super keyword)

In your case, inside the child class, simply access the property in the parent using super.data

  • Related