为什么我需要这个。关键字引用具有相同名称的变量?

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

晚上好,

这是我第一次 post 堆栈溢出。我是编程新手,我可以用 C++ 做很多事情——我喜欢的一种语言。 但是,最近我开始 javascript 并肩负着被录用的使命。

我正在创建一个贪吃蛇游戏,并将其动作自动化。 我只是不明白为什么我在函数内部创建的变量,就在几个 if 语句之上,不是 使用了 inside 语句。我不得不用这个。关键字来改变它的状态。 谢谢!

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);
  }
});

因为this.intervallet interval根本不是一回事

第一个是任何对象 this is, and the second is a block-scoped local variable 的 属性,只有该函数的生命周期;就像 C++ 中的局部函数(没有 static)一样。

由于您使用的是常规 function()(而不是箭头函数),调用者决定 this 在调用时绑定到什么(参见前面链接的 this 页面).