【发布时间】:2015-03-31 01:53:25
【问题描述】:
我是 JavaScript 新手,我正在尝试编写一个简单的游戏循环。这是我的游戏对象:
var Game = {
timers: [],
start: timestamp(),
stopTimers: function() {
consoleEntry('All timers have been stopped.');
this.timers.length = 0;
},
update: function(elasped) {
for (var i = 0; i < this.timers.length; ++i) {
var timer = elapsed - timers[i].startTime;
console.log('Timer: ' + timer + '. Timer interval: ' + this.timers[i].interval + '.');
if (this.timers[i].interval <= timer) {
this.timers[i].times--;
this.timers[i].report = true;
if (this.timers[i].times != 0) {
this.timers[i].startTime = elapsed;
}
}
}
},
render: function() {
for (var i = 0; i < this.timers.length; ++i) {
if (this.timers[i].report) {
consoleEntry('Timer: ' + this.timers[i].name + ' (' + this.timers[i].times + ' remaining).');
this.timers[i].report = false;
if (this.timers[i].times == 0) this.timers.splice(i, 1);
}
}
},
gameLoop: function() {
var elapsed = timestamp() - this.start;
this.update(elapsed);
this.render();
requestAnimationFrame(this.gameLoop);
},
startGame: function() {
console.log(this);
requestAnimationFrame(this.gameLoop);
}
}
当<body> 加载时,我调用Game.startGame();。这是我收到的错误:Uncaught TypeError: undefined is not a function。它指的是gameLoop 函数中的this.update(elapsed);。出于某种原因我不明白,当我在startGame 中执行console.log(this) 时,我得到了它所属的对象(这很棒),但是当我在gameLoop 中执行相同操作时,我得到了Window 对象.
有人知道为什么会这样吗?
谢谢!
【问题讨论】:
-
你是在调用 new Game,然后在你刚刚创建的新对象上调用 startGame 吗?或者你真的只是在调用 Game.startGame()?
-
字面意思 :) 我不应该,嗯?
-
你必须将
this绑定到你传递给requestAnimationFrame()的函数-requestAnimationFrame(this.gameLoop.bind(this)); -
@Jazzepi
Game变量指的是普通对象,而不是构造函数。 -
我只是不明白为什么
this在gameLoop中返回Window
标签: javascript object methods this