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(PL
n)
; but I'm looking for a way to do this somehow automatically. Is there a built-in function? Should I use a loop?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With