gpt4 book ai didi

javascript - JS原型(prototype)无法设置未定义的属性 'moveRight'

转载 作者:行者123 更新时间:2023-12-03 10:40:34 25 4
gpt4 key购买 nike

我对这个简单的原型(prototype)设计有疑问:

Game = function (moduleConfig, gameConfig) {
this.moduleConfig = moduleConfig;
this.gameConfig = gameConfig;

// Game-Commands
this.keyCommands = {
moveLeft: false,
moveRight: false
};

this.catcher = null;
this.stage = null;
return this;
}

/**
* Left arrow down
*/
Game.prototype.onKeyboardLeftDown = function () {
this.keyCommands.moveLeft = true;
}

/**
* Left arrow up
*/
Game.prototype.onKeyboardLeftUp = function () {
this.keyCommands.moveLeft = false;
}

调用 onKeyboardLeftDownonKeyboardLeftUp 时,我总是收到错误消息:Uncaught TypeError: Cannot set property 'moveRight' of undefined。但我已经在 keyCommands 对象的构造函数中声明了 moveLeft

这两个方法在按下键和按下键事件时调用:

Game.prototype.init = function () {

// ...

// =========================================================================
// Set keyboard
KeyboardJS.on('left', this.onKeyboardLeftDown, this.onKeyboardLeftUp);
KeyboardJS.on('right', this.onKeyboardRightDown, this.onKeyboardRightUp);
// =========================================================================
};

我的index.html 看起来像这样:

<!DOCTYPE html>
<html>
<head>
<title>pixi.js example 1</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000000;
}
</style>
<script src="js/pixi.dev.js"></script>
<script src="js/keyboard.js"></script>
<script src="js/moduleConfig.js"></script>
<script src="js/moduleResult.js"></script>
<script src="js/game.js"></script>
</head>
<body style="background-color: #EEEEEE">
<script>

var game = new Game(moduleConfig, {
screenWidth: (window.innerWidth - 10),
screenHeight: (window.innerHeight - 10),
bgColor: 0xEEEEEE
});

game.init();
</script>

</body>
</html>

有人看到失败了吗?我搜索了很多,但我很困惑(通常我只用c#开发......)

最佳答案

您的绑定(bind)是错误的。

// Set keyboard
KeyboardJS.on('left', this.onKeyboardLeftDown, this.onKeyboardLeftUp);

this.onKeyboardLeftDownthis.onKeyboardLeftUp 在没有正确上下文的情况下调用

要解决此问题,请执行以下操作:

KeyboardJS.on('left', this.onKeyboardLeftDown.bind(Game), this.onKeyboardLeftUp.bind(Game));

我不建议使用bind() - 为了浏览器兼容性,但您可以使用lodash的bind或bind“模拟器”之类的东西:

function bind(fn, ctx) {
return function bound() {
return fn.apply(ctx, arguments);
};
}

另一种方式是

var self = this;
KeyboardJS.on('left',
function(){self.onKeyboardLeftDown()},
function(){self.onKeyboardLeftUp()}
);

关于javascript - JS原型(prototype)无法设置未定义的属性 'moveRight',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799911/

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