JS getter没有返回动态结果

问题描述 投票:-1回答:1

我正在制作一个简单的游戏,它分为生成价值的游戏生成器和与用户交互的游戏引擎。

class Generator {
  constructor() {
    this.intro = 'Answer "yes" if number even otherwise answer "no"!';
    this.question = null;
    this.answer = null;
  }
  get game() {
    this.question = getRandomInt(10);
    this.answer = this.question % 2 === 0 ? 'yes' : 'no';
    return [this.question, this.answer];
  }
}

const newGame = new Generator();

const gameEven = () => game(newGame.intro, newGame.game);

但是,当我启动游戏时,我发现它循环使用相同的数字。我特意使用get game()因为MDN声明允许返回dynamically computed value,为什么它不起作用?

javascript getter
1个回答
0
投票

不确定你有什么问题,但我不认为这是JS getter not returning dynamic result

下面是一个简单的Snippet,演示了getter的动态特性。

正如您所看到的,当您致电game时,您会得到2个不同的随机数

class Generator {
  get game() {
    return Math.random();
  }
}

var v = new Generator();
console.log(v.game);
console.log(v.game);
© www.soinside.com 2019 - 2024. All rights reserved.