Passing an object to a constructor and then calling functions with bind

I am trying to pass a function to an object through a constructor in order to use it inside a class using bind. Here is my code.

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
}

then I want to be able to call one of the "move" functions in the InputManager

InputManager.prototype.doKeyDown = function (e) {

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

But I get the following error: Uncaught TypeError: this.moveLeft is not a function. When printing, I get undefined. What am I doing wrong, or is there another way to do this?

+4
source share

All Articles