我简化了我的代码以说明问题。
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函数中,这指的是窗口。我理解为什么它指的是窗口,但我想不出解决方案......
完整的代码可以在这里看到:http://eriknijland.nl/stackoverflow/snake_event_listener/
答案 0 :(得分:2)
虽然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?)
答案 1 :(得分:0)
试试这个:
function SnakeGame ()
{
var self = this;
this.snakeDirection = 'right';
this.Init = function ()
{
window.addEventListener('keydown', this.keyboardInput, false);
}
this.keyboardInput = function (event)
{
console.log(self);
console.log(event.keyCode); //Works
}
}
答案 2 :(得分:0)
如果定位ES5(你应该这样做),你应该写:
window.addEventListener('keydown', this.keyboardInput.bind(this), false);
将确保始终使用this
作为其上下文调用回调。