Dankey Dankey - 2 months ago 19
Node.js Question

Property is becoming NaN

I have the following code for a small game server.

var GameWorld = function () {

this.uptime = 0;

this.loop = function () {
this.uptime++;
};

};

var game = new GameWorld();
setInterval(game.loop, 500);


However then when I look at
game.uptime
, it returns NaN

Answer

This is happening because when game.loop is called with the given interval, this does not return the correct object (read Understanding JavaScript's "this")

To change this, you simply need to bind game when calling game.loop:

setInterval(game.loop.bind(game), 500);