I have simplified my code to illustrate the problem.
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
}
}
Within the this.keyboardInput function I try to change the variable this.snakeDirection; problem is that I can’t get a reference to the SnakeGame object. Within the keyboardInput function this refers to window. I understand why it refers to window, but I can’t think of a solution…
The full code can be seen here: http://eriknijland.nl/stackoverflow/snake_event_listener/
Though Mythril’s answer is correct, I’d suggest you not to use methods as event callbacks. Because: a) they’re public, so can be overruled quite easily once your code gets bigger and b) they’re publicly accessible:
So I’d use a closure:
Also bear in mind that your code isn’t exactly X-browser compatible (addEventListener && attachEvent?)