Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array of Instances of a class

In JS, I have a class called player which is:

class player {
    constructor(name) {
        this.name = name;
    }
}

and I have two instances of it, called PL1 and PL2:

const PL1 = new player ('pl1name');
const PL2 = new player ('pl2name');

I also have an array called PLAYERS:

let PLAYERS = [];

now, the question is how can I create an array with all of the instances of the class player?

I know I can manually do this with PLAYERS.push(PLn); but I'm looking for a way to do this somehow automatically. Is there a built-in function? Should I use a loop?

like image 954
Shahriar Avatar asked Sep 18 '18 00:09

Shahriar


1 Answers

You could create a class that is a container class for the players. This will allow the container to create players and manage them. The the Players class can expose an interface making it easy to interact with the players individually or as a whole. Something like this might be a good start and could be filled out with more functionality or different orginziation:

// 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())
like image 175
Mark Avatar answered Sep 29 '22 09:09

Mark