0

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?

seddouguim
  • 504
  • 3
  • 12

1 Answers1

2
    document.addEventListener("keydown", this.changeDirection());

doesn't do what you expect, you are calling the function here, just the first time, not passing it to addEventListener.

You would want to

document.addEventListener("keydown", this.changeDirection);

first, so that will be called on the keydown event instead, and finally just bind it:

document.addEventListener("keydown", this.changeDirection.bind(this));
Federkun
  • 36,084
  • 8
  • 78
  • 90
  • Thank you that worked! I just don't understand why binding it is necessary? – seddouguim May 30 '21 at 20:31
  • 1
    Binding is necessary because otherwise `this.dx` will not refer to the original instance of the class. If you pass `this.changeDirection`, you lose that context – Federkun May 30 '21 at 20:32