JS原型无法设置属性'moveRight'的未定义

JS prototyping Cannot set property 'moveRight' of undefined

本文关键字:未定义 moveRight 属性 原型 设置 JS      更新时间:2023-09-26

我对这个简单的原型设计有一个问题:

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#中开发…)

您的绑定是错误的。

// 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或类似的绑定"模拟器"

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

另一种方式是

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

您的问题不完整,我看不到您试图定义moveRight的相关代码。

可能的问题:

  • 你可能有拼写错误,keyCommands拼写正确
  • 您可以在keyCommands的范围之外引用它
  • 在初始化keyCommands之前,可以参考keyCommands.moveRight
  • 在引用moveRight之前,可以为keyCommands指定另一个值