I wrote some code for a class called Player
, which initializes some attributes upon usage. One of the attributes is an array. Here's my simplified code:
class Player {
constructor(basicStuff) {
this.basicStuff = basicStuff
this.keys = [];
}
move(event) {
this.keys[event.key] = true;
//moves position
}
releaseKey(event) {
//updates the keys pressed
}
draw(scene) {
//draws player
}
}
const player = new Player("basicStuff");
window.addEventListener('keydown', player.move);
window.addEventListener("keyup", player.releaseKey);
So here's the problem: when I run the code and test it, I would get "Uncaught TypeError: Cannot set property 'event.key' of undefined"
. It seems like this.keys
from the const player
was never defined even though it's very clear that I've done so in the constructor. What should I do so this.keys
in the move
method of player
is not undefined
?
Note: This piece of Javascript code is cooperating with another Node.js file, if that's helpful to mention.