2012-02-06 114 views
2

我正在用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访问父类的方式?

谢谢你的时间!

+3

'如果(真)'.... – jAndy 2012-02-06 22:06:17

+0

我敢肯定这无关我的js OOP ... – Loupax 2012-02-06 22:08:28

回答

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

咦,它的工作!有一段时间我以为它会给我同样的错误,因为我认为自我的类型会更新,但我可以访问更新就好!谢谢! – Loupax 2012-02-06 22:15:41