Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to add array of object in class in javascript

// An individual player. Holds properties and behavior for one player
class Player {
  constructor(name) {
      this.name = name;
  }
  play() {
    console.log(this.name, "plays")
  }
}

// Class that holds a collection of players and properties and functions for the group
class Players {
  constructor(){
    this.players = []
  }
  // create a new player and save it in the collection
  newPlayer(name){
    let p = new Player(name)
    this.players.push(p)
    return p
  }
  get allPlayers(){
    return this.players
  }
  // this could include summary stats like average score, etc. For simplicy, just the count for now
  get numberOfPlayers(){
      return this.players.length
  }
}

let league = new Players()
league.newPlayer("Mark")
league.newPlayer("Roger")

// list all the players
console.log(league.numberOfPlayers + " Players)
console.log(league.allPlayers)


// make them do something
league.allPlayers.forEach(player => player.play())
 Run code snippet
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #add #array #object #class #javascript
ADD COMMENT
Topic
Name
4+7 =