【发布时间】:2016-08-19 04:22:43
【问题描述】:
我试图递归调用一个函数,直到游戏结束,但是,在执行过程中,“this”被重置为“window”,这导致以下错误:“无法读取未定义的属性'step'。”
我已经尝试将有问题的行重写为
this.game.bind(this).step();
还有
this.game.step.bind(this);
两者都不起作用。对于上下文,step 只是一个函数,它在 Game 中调用两个帮助器来移动对象并寻找碰撞,当我使用它们而不是 step 时,错误仍然存在。
/* globals key */
const Game = require('./game.js');
let speed = 1;
function GameView(ctx) {
this.ctx = ctx;
this.game = new Game();
}
GameView.prototype.start = function (callback) {
// let that = this
this.bindKeyHandlers();
this.animate(0);
};
GameView.prototype.animate = function(time) {
speed += 1;
if (speed >= 605) {
speed = 0;
};
this.game.step();
this.game.draw(this.ctx, speed);
if(!this.game.lose()){
requestAnimationFrame(this.animate());
}
else {
this.ctx.fillStyle = "white";
this.ctx.font = "italic "+24+"pt Arial ";
this.ctx.fillText(`Game Over \n Press Enter to restart`, 100,200 );
key('enter', ()=>{
this.game = new Game();
this.start();
});
}
};
GameView.prototype.bindKeyHandlers = function() {
key('d', () => {
this.game.ship.power([2, 0]);
});
key('a', () => {
this.game.ship.power([-2, 0]);
});
key('s', () => {
this.game.ship.power([0, 2]);
});
key('w', () => {
this.game.ship.power([0, -2]);
});
key('l', () => {
this.game.ship.fireBullet();
});
};
module.exports = GameView;
【问题讨论】:
-
.bind()在哪里使用javascript?传递给requestAnimationFrame的参数应该是对函数的引用吗? -
你确定
new Game()正在生成一个对象吗? -
您是否意识到
.bind()返回一个您需要调用的新函数?您尝试的两个示例实际上都没有调用.bind()返回的函数。 -
应该是
requestAnimationFrame(this.animate.bind(this));
标签: javascript binding this