我正在制作一个简单的游戏,它分为生成价值的游戏生成器和与用户交互的游戏引擎。
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,为什么它不起作用?
不确定你有什么问题,但我不认为这是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);