我试图理解 javascript 对象,但我遇到了一个问题。 为什么这个变量返回“NaN”?
function Game(){
this.players = 0;
this.round = 0;
this.turn = this.round / this.players;
}
var game = new Game();
game.players = 5;
game.round = 10;
console.log(game.turn);
game.turn 应该是 2 而不是 NaN。
问题是“this.players”和“this.round”没有改变,因为你不能除以 0,所以它返回 NaN。
我重写了它,令人惊讶的是它有效。
function Game(){
this.players = 0;
this.round = 0;
this.turn = function(){
return this.round / this.players;
}
}
var game = new Game();
game.players = 5;
game.round = 10;
console.log(game.turn());
为什么代码的第二部分可以工作,而第一部分却不能?
最佳答案
因为第一个代码片段在初始化时运行,所以实例化后更改值不会更改 turn
的值。
在第二个示例中,您正在按需计算turn
,因此仅在您调用该函数时才计算它,并且您在设置players<的值后调用该函数
和 圆形
。
关于javascript - 更改 javascript 对象的变量(this.variable)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32228114/