对Javascript中的变量可见性感到困惑

时间:2012-02-06 22:03:55

标签: javascript

我正在使用Javascript构建一个简单的游戏引擎,并且我找到了一个名为“所有函数都是对象类”的墙。

更具体地说,我有班级

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));

            }           
        };

}

我正在考虑使用全局对象作为更新和绘制函数的容器,但这对我来说感觉不对...还有其他方法吗?是否有本地JS方式访问父类?

谢谢你的时间!

1 个答案:

答案 0 :(得分:2)

这里的问题是你使用回调就好像它是一个成员函数。这会因为您的演示而中断,因为回调使用this的不同值执行。如果要在回调中使用原始this,则需要将其存储在本地并在回调中使用该本地。

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 ...
  }
};