对Javascript中的变量可见性感到困惑
我正在用Javascript构建一个简单的游戏引擎,我碰到了一堵名为“所有函数都是对象类”的墙 更具体地说,我有这门课对Javascript中的变量可见性感到困惑,javascript,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.f
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方式访问父类
谢谢你的时间 这里的问题是,您使用的回调函数就像是一个成员函数一样。正如您所演示的那样,这将中断,因为回调将以不同的值执行
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 ...
}
};
我很确定这与我的js OOP无关…哈,它成功了!有那么一刻,我认为它会给我同样的错误,因为我认为自我的类型将是更新,但我可以访问更新刚刚好!非常感谢。