0
我試圖遞歸調用一個函數,直到遊戲結束,但是,在執行過程中「this」被重置爲'window',這導致了以下錯誤:「can not read property未定義的'步驟'。「Javascript綁定問題沒有通過調用綁定解決
我試圖重寫違規行
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;
'javascript'使用'.bind()'在哪裏?傳遞給'requestAnimationFrame'的參數應該是對函數的引用嗎? – guest271314
你確定'new Game()'產生一個對象嗎? – Mike
你知道'.bind()'返回一個新函數,然後你需要調用嗎?你試過的例子都沒有調用'.bind()'返回的函數。 – jfriend00