我在Javascript中编写了一个Pong版本。我有一个Game对象,我使用prototype属性来定义它的方法。我收到以下错误:"未定义不是函数"。它被抛入Game.prototype.step函数中,因此this.update在那里是未定义的。这是Game对象的代码:
(function(root) {
var Pong = root.Pong = (root.Pong || {});
var Game = Pong.Game = function() {
this.canvas = document.getElementById('canvas');
this.canvas.width = 800;
this.canvas.height = 400;
this.context = canvas.getContext('2d');
this.maxStartSpeed = 10;
this.keysDown = {};
this.player2 = new Pong.Player({'player': 2});
this.player1 = new Pong.Player({'player': 1});
this.ball = new Pong.Ball(400, 200);
}
Game.prototype.update = function() {
this.player1.update();
this.player2.update();
this.ball.update(player1.paddle, player2.paddle);
};
Game.prototype.render = function() {
this.context.fillStyle = "#bdc3c7";
this.context.fillRect(0, 0, width, height);
this.player1.render();
this.player2.render();
this.ball.render();
};
Game.prototype.animate = function(callback) {
window.setTimeout(callback, 1000/60)
};
Game.prototype.step = function() {
this.update();
this.animate(this.step);
};
window.addEventListener("keydown", function (event) {
Game.keysDown[event.keyCode] = true;
});
window.addEventListener("keyup", function (event) {
delete Game.keysDown[event.keyCode];
});
window.onload = function() {
document.getElementById('canvas-container').appendChild(canvas);
game = new Game();
game.animate(game.step);
};
})(this);
答案 0 :(得分:1)
setTimeout将改变范围。要保持适当的范围,您需要使用bind
更改
this.animate(this.step);
到
this.animate(this.step.bind(this));
你需要对其他动画调用做同样的事情。