Reputation: 2071
Im trying to understand javascript objects but I got stuck on a problem. Why is this variable returning "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 should be 2 not NaN.
The problem is that "this.players" and "this.round" is not changing and since you cant divide by 0 it returns NaN.
I rewrote it and surprisingly this worked.
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());
Why does the second part of code work but not the first?
Upvotes: 0
Views: 212
Reputation: 10184
In the first code sample you posted, you are directly assigning the value of 'turn.
' It is never recomputed merely for your having assigned different values to 'players
' and 'round
'.
In your second version, you have written a function
that is invoked
each time turn()
is called that recomputes the value based on the current values of players
and round
.
Upvotes: 1
Reputation: 9597
Because the first snippet is running on initialization, so changing the values after instantiation is not going to change the value of turn
.
In your second example, you are computing turn
on demand, so its only calculated when you invoke the function and you are invoking the function after you've set the values of players
and round
.
Upvotes: 2
Reputation: 943935
The first approach evaluates the statement this.turn = this.round / this.players;
when the Game
function is called. You call it before you change the values of players
and round
.
The second approach evaluates the statement return this.round / this.players;
when the turn
function is called, which is after you set those values.
For the first approach to work, you'd need to use a getter or setter to calculate the value of turn
either when it is got or when one of the other values is set.
function Game() {
this.players = 0;
this.round = 0;
}
Object.defineProperty(Game.prototype, "turn", {
get: function get_turn() {
return this.round / this.players;;
}
});
var game = new Game();
game.players = 5;
game.round = 10;
console.log(game.turn);
Upvotes: 1