I’m creating a simple game to practice using classes. In this game, the Game
class should create a new instance of the Round
class so that each round of the game start anew, with the default values for its fields and properties.
Problem
For some reason, new instances of the Round
class after creating the original does not reset the roundOn
property. Why doesn’t the constructor function in Round
initialize this.roundOn = true
for the second instance? Really stumped on what class behavior I’m overlooking.
It also doesn’t help to declare roundOn
in the class body. Additionally, the Round
constructor function does trigger as evidenced by the log statements.
MY CODE:
class Round {
constructor () {
console.log('-- constructor triggered! --')
this.roundOn = true
}
changeVar () {
this.roundOn = false
}
}
class Game {
constructor () {
this.currentRound = new Round()
}
newRound () {
this.currentRound = new Round()
}
}
const currentGame = new Game()
const round = currentGame.currentRound
console.log('first instance:', round.roundOn)
round.changeVar()
console.log('after changeVar():', round.roundOn)
currentGame.newRound()
console.log('second instance (should be true):', round.roundOn)
OUTPUT:
-- constructor triggered! --
first instance: true
after changeVar(): false
-- constructor triggered! --
second instance (should be true): false