Skip to content
Advertisement

Why do I need this. keyword to reference a variable with the same name?

Good evening,

This is my first post on stack overflow. I’m a newbie in programming and I can do many things in C++ – a language I love. However, recently I’ve moved on to javascript with the mission of getting hired.

I’m creating a snake game and I’m automatizing its moves. I just do not understand why a variable I created inside a function, just above a few if statements, isn’t used inside the statements. I had to use this. keyword to change its state. Thank you!

document.getElementById("action").addEventListener("keydown", function (event) {
  let interval = null; // the culprit

  if (event.key === "ArrowDown") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowDown, 1000);
  } else if (event.key === "ArrowRight") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowRight, 1000);
  } else if (event.key === "ArrowUp") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowUp, 1000);
  } else if (event.key === "ArrowLeft") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowLeft, 1000);
  }
});

Advertisement

Answer

Because this.interval and let interval are not the same thing at all.

The first is a property of whatever object this is, and the second is a block-scoped local variable with a lifetime of just that function; just like a local function (without static) would have in C++.

Since you’re using a regular function() (and not an arrow function), the caller decides what this is bound to at call time (see the aforelinked this page).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement