I'm trying to build a simple JS snake game using classes. I've ran into a problem in which a variable declared in the constructor does not change. Here's my code:
class Snake {
constructor() {
this.canvas = document.getElementById("graph");
this.ctx = this.canvas.getContext("2d");
this.snakeCoordinates = [{ x: 250, y: 250 }];
this.dx = 10;
this.dy = 0;
this.drawSnake();
document.addEventListener("keydown", this.changeDirection());
}
changeDirection() {
this.dx = -10;
}
I added an event listener that calls my changeDirection function. However, when I console.log the dx variable, it remains unchanged.
Can someone tell me what I'm doing wrong?