Horje
how to add array of object in class in javascript Code Example
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




Javascript

Related
triangle sum of odds numbers formula Code Example triangle sum of odds numbers formula Code Example
how to get the folder of the extension Code Example how to get the folder of the extension Code Example
how to add jquery to an html css and javascript project Code Example how to add jquery to an html css and javascript project Code Example
react native asyncstorage setItem Code Example react native asyncstorage setItem Code Example
node get request filepath Code Example node get request filepath Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
7