我在下面有一个类来控制一个小的HTML5游戏。您将在startGame方法中看到一些对象被保存到名为keys的属性,这是Keys类的一个实例。
在此之后,我调用此类中另一个名为setEventHandlers的方法。理论上,这应该设置将调用回调的处理程序,回调将数据发送到密钥对象(存储为属性)。
每当调用this.keys.keyDown
或this.keys.keyUp
时,它都会声明“键”未定义。
我似乎无法找到为什么会发生这种情况,它看起来与执行顺序有关。有任何想法吗?提前谢谢。
function Game() {
this.startGame();
}
Game.prototype.startGame = function () {
this.canvasElement = document.createElement("canvas");
this.canvasContext = this.canvasElement.getContext("2d");
document.body.appendChild(this.canvasElement);
this.canvasElement.width = window.innerWidth;
this.canvasElement.height = window.innerHeight;
this.keys = new Keys();
this.mouse = new Mouse();
this.player = new Player(this.randomPosition().x, this.randomPosition().y);
this.setEventHandlers();
};
Game.prototype.setEventHandlers = function () {
var onKeyDown = function (e) {
this.keys.keyDown(e.keyCode);
},
onKeyUp = function (e) {
this.keys.keyUp(e.keyCode);
},
onMouseMove = function (e) {
// this.mouse.move(e.x, e.y);
},
onMouseClick = function (e) {
// this.mouse.click(e.x, e.y);
},
onWindowResize = function () {
this.canvasElement.width = window.innerWidth;
this.canvasElement.height = window.innerHeight;
};
// Keyboard events
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
// Mouse events
window.addEventListener("mousemove", onMouseMove, false);
window.addEventListener("click", onMouseClick, false);
// Window events
window.addEventListener("resize", onWindowResize, false);
};
Game.prototype.randomPosition = function () {
var randomX = Math.round(Math.random() * this.canvasElement.width),
randomY = Math.round(Math.random() * this.canvasElement.height);
return { x: randomX, y: randomY };
};
答案 0 :(得分:3)
var onKeyDown = function (e) {
this.keys.keyDown(e.keyCode);
},
上面的代码创建了一个新函数,因此“this”指的是自身而不是游戏对象 尝试
var self = this;
var onKeyDown = function (e) {
self.keys.keyDown(e.keyCode);
},