将对象传递给构造函数,然后使用bind调用函数

时间:2016-07-06 15:39:38

标签: javascript

我试图通过构造函数将一个函数传递给一个对象,以便在类中使用bind来使用它。这是我的代码。

gameManager.js

    var GameManager = function() {

        this.inputManager = new InputManager(   this.moveRight.bind(this), this.moveDown.bind(this),
                                            this.moveLeft.bind(this), this.moveUp.bind(this));
    }

GameManager.prototype.moveLeft = function () {
    ...
}

inputManager.js

var InputManager = function(moveRight, moveDown, moveLeft, moveUp) {

    this.moveRight = moveRight
    this.moveDown = moveDown
    this.moveLeft = moveLeft
    this.moveUp = moveUp
}

然后我希望能够在InputManager中调用其中一个“move”函数

InputManager.prototype.doKeyDown = function (e) {

    if ( (e.keyCode === 65) || (e.keyCode === 37)) { //A, left arrow
     console.log(this.moveLeft)   
     this.moveLeft()
    }
}

但是我收到以下错误: Uncaught TypeError: this.moveLeft is not a function. 打印时我得到了不确定。 我做错了什么,或者有其他办法吗?

0 个答案:

没有答案