hackerKing
hackerKing

Reputation: 11

create multiple objects with loop in constructor function

I have a problem when trying to create multiple objects in the function of a constructor function.

I'm trying to create multiple objects that each one has the array hand, and each one has the name player(x), so it would be player0: [array], player1:[array], but it does not work. I get the error

Cannot set property '0' of undefined

Code:

function Player () {
  this.hand = []
}

function Players () {

}

Players.prototype.createPlayers = function (x) {
    for (let i = 0; i < x; i++) {
      this.player[i] = new Player()
  }
}

let gamer = new Players()
console.log(gamer)

gamer.createPlayers(3)
console.log(gamer.players)

Upvotes: 0

Views: 340

Answers (1)

Abdelrhman ElSayed
Abdelrhman ElSayed

Reputation: 439

This is working try it, Is this you want?

function Player () {
  this.hand = []
}

function Players () {
  this.player = [];
}

Players.prototype.createPlayers = function (x) {
    for (let i = 0; i < x; i++) {
      this.player[i] = new Player()
  }
}

let gamer = new Players()
console.log(gamer)

gamer.createPlayers(3)
console.log(gamer.players)

Upvotes: 1

Related Questions