我简化了代码来说明问题。
function SnakeGame ()
{
this.snakeDirection = 'right';
this.Init = function ()
{
window.addEventListener('keydown', this.keyboardInput, false);
}
this.keyboardInput = function (event, SnakeGameObject)
{
console.log(SnakeGameObject); //Error since I can't pass this variable...
console.log(event.keyCode); //Works
}
}
在 this.keyboardInput 函数中,我尝试更改变量 this.snakeDirection;问题是我无法获得对 SnakeGame 对象的引用。在 KeyboardInput 函数中,this 指的是窗口。我明白为什么它指的是窗口,但我想不出解决方案......
完整代码可以在这里看到:http://eriknijland.nl/stackoverflow/snake_event_listener/
最佳答案
虽然 Mythril 的答案是正确的,但我建议您不要使用方法作为事件回调。因为:a)它们是公开的,因此一旦您的代码变得更大,就可以很容易地被否决;b)它们可以公开访问:
var snakeInstance = new SnakeGame();
var otherObject = new SomethingElse();
snakeInstance.keyboardInput.apply(otherObject,[]);//invokes method, uses self, though self !== otherObject, but snakeInstance.
所以我会使用闭包:
function SnakeGame()
{
this.snakeDirection = 'right';
var keyBoardInput = (function(that)
{
return function(e)
{
console.log(that);
console.log(e.keyCode);
}
})(this);
this.Init = function()
{
document.body.addEventListener('keydown',keyboardInput,false);
}
}
另请记住,您的代码与 X 浏览器不完全兼容(addEventListener && AttachEvent?)
关于JavaScript addEventListener 添加对当前对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12231561/