I've been using JS for a little bit ( 9 months), and was writing a game when I realized this. I had a Level
object, which had a property player
. The player needed to react to key events, so I wrote this up:
export class Level{
constructor(){
this.player = new Player();
window.addEventListener('keydown', this.keyHandeler);
window.addEventListener('keyup', this.keyHandeler);
}
keyHandeler(event){
const down = event.type == 'keydown';
switch(event.keyCode){
case 37: this.player.keys.left = down; break;
case 38: this.player.keys.up = down; break;
case 39: this.player.keys.right = down; break;
case 40: this.player.keys.bottom = down; break;
}
}
}
However, when I ran this code I kept getting an error along the lines of Can not read property "keys" of undefined
, meaning that this.player
was undefined. I then logged this
inside of the keyHandeler
function, and got the window object. I can see how this might make sense, but the function is still a part of Level
. If this is just the way it is, how do I accomplish this?