我试图通过构造函数将一个函数传递给一个对象,以便在类中使用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.
打印时我得到了不确定。
我做错了什么,或者有其他办法吗?