gpt4 book ai didi

类内的 JavaScript 对象是 'undefined'

转载 作者:行者123 更新时间:2023-11-30 12:48:03 25 4
gpt4 key购买 nike

<分区>

我下面有一个类控制一个小型 HTML5 游戏。您会在 startGame 方法中看到几行,一个对象被保存到一个名为 keys 的属性中,这是 Keys 类的一个实例。

在此之后,我调用了此类中的另一个方法,称为 setEventHandlers。理论上,这应该设置将调用回调的处理程序,回调将数据发送到键对象(存储为属性)。

每当调用 this.keys.keyDownthis.keys.keyUp 时,它都会声明“keys”未定义。

我似乎无法找到发生这种情况的原因,看起来与执行顺序有关。有任何想法吗?提前致谢。

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 };
};

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com