Loupax
Loupax

Reputation: 4924

Confused about variable visibility in Javascript

I'm building a simple game engine in Javascript, and I've hit a wall named 'all functions are object classes'.

More specifically, I have the class

function Game(){

}

Game.prototype = {
 update: function(){/* Blah */},
 draw:   function(){/* Foo */},

 start: function(fps){
        //Just a global var where I keep the FPS
        GS.fps = fps;
        var start = new Date().getTime();
        var time = 0;
        function timer(){
            time += (1000/fps);
            var diff = (new Date().getTime() - start) - time;
            if(true)
            {
                //Execute on itteration of the game loop
                this.update();  //It breaks here because this. is timer, not G.Game

                //Draw everything
                this.draw();

                window.setTimeout(timer,(1000/GS.fps - diff));

            }           
        };

}

I'm thinking of using global objects as containers for the update and draw functions, but this just feels wrong to me... Is there any other way? Is there a native JS way of accessing the parent class?

Thanks for your time!

Upvotes: 2

Views: 196

Answers (1)

JaredPar
JaredPar

Reputation: 755457

The problem here is that you are using a callback as if it's a member function. This will break as you've demonstrated because the callback executes with a different value for this. If you want to use the original this in the callback you need to store it in a local and use that local in the callback.

var self = this;
function timer(){
  time += (1000/fps);
  var diff = (new Date().getTime() - start) - time;
  if(true)
  {
     //Execute on itteration of the game loop
     self.update();  
     self.draw();
     etc ...
  }
};

Upvotes: 2

Related Questions