Search
 
SCRIPT & CODE EXAMPLE
 

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
Comment

PREVIOUS NEXT
Code Example
Javascript :: Cannot find module Cannot find module 
Javascript :: how to square a number in html 
Javascript :: Remove all index from array except the one jquery 
Javascript :: how to append response header in node in every request 
Javascript :: vanilla js for each element add attribute 
Javascript :: convert milliseconds to hours minutes seconds javascript 
Javascript :: conditional json spread operator 
Javascript :: @testing-library/react-native switch 
Javascript :: javascript concurrency 
Javascript :: state functions of react cheatsheet 
Javascript :: js file not found in laravel on live laravel project 
Javascript :: change the body background color with javascript 
Javascript :: UnhandledPromiseRejectionWarning: SequelizeDatabaseError: type "enum" already exists 
Javascript :: js convert charcode to char 
Javascript :: does mysql accept json 
Javascript :: @Scheduled cron expresssion 
Javascript :: aws lambda create 
Javascript :: event on trible click in js 
Javascript :: erpnext date difference client script 
Javascript :: vscode nestjs ignore node_modules 
Javascript :: how to stop re rendering in react hooks 
Javascript :: javascript intersect two object arrays 
Javascript :: jstree get not disabled nodes 
Javascript :: know if a gridview is empty from javascript 
Javascript :: get decimal on number javscri 
Javascript :: bootstrap dropdown with state 
Javascript :: explicitly import from lodash 
Javascript :: math.factorial javascript 
Javascript :: infinite loop MenuItem MUI fixed onClick event 
Javascript :: react jsx hello react sample 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =