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

时间:2015-03-01 22:25:13

标签: javascript class properties prototype undefined

我对这个简单的原型设计存在问题:

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

在致电Uncaught TypeError: Cannot set property 'moveRight' of undefinedonKeyboardLeftDown时,我始终收到错误消息:onKeyboardLeftUp。但是我在moveLeft对象的构造函数中声明了keyCommands

这两种方法在按键和按键事件时被调用:

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

2 个答案:

答案 0 :(得分:1)

你的绑定是错误的。

// 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的绑定或绑定&#34;模拟器&#34;像:

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

另一种方式是

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

答案 1 :(得分:0)

您的问题不完整,我没有在您尝试定义moveRight的地方看到相关代码。

可能出现的问题:

  • 您可能会输入错误,keyCommands拼写错误
  • 您可以在其范围之外引用keyCommands
  • 您可以在keyCommands.moveRight初始化之前参考keyCommands
  • 在引用keyCommands
  • 之前,您可以为moveRight分配另一个值