javascript - 有没有办法使用命名箭头函数来维护对象内的词法范围?

标签 javascript object this

描述: 我正在使用 window.addEventListener() 并希望调用命名函数(而不是匿名函数),因为我希望能够在稍后阶段使用removeEventListener。 然而,eventHandler 中的console.log(箭头函数)显示“this”仍然指向窗口对象而不是游戏对象。

PS:在我重构时忽略代码的其他部分,其余部分可能仍然不完整, 我知道我可以使用构造函数,但我正处于学习阶段,在研究构造函数之前,我想看看是否可以在没有构造函数的情况下完成此操作

function makeGameObject() {

  return {

    score: 0,
    level: 1,


    start() {
      for (let coin of coins) {
        this.moveCoin(coin);
      }
      window.addEventListener("keydown", this.gameOn)
    },

    stop() {
      window.removeEventListener("keydown", this.gameOn);

    },


    gameOn: (evt) => {
      console.log(this);
      if (evt.key.toUpperCase() === "W" || evt.key === "ArrowUp") {
        this.moveObject(player, 30, 'up');
      } else if (evt.key.toUpperCase() === "S" || evt.key === "ArrowDown") {
        this.moveObject(player, 30, 'down');
      } else if (evt.key.toUpperCase() === "A" || evt.key === "ArrowLeft") {
        this.moveObject(player, 30, 'left');
        player.style.transform = 'scale(-1,1)';
      } else if (evt.key.toUpperCase() === "D" || evt.key === "ArrowRight") {
        this.moveObject(player, 30, 'right');
        player.style.transform = 'scale(1,1)';
      }

      for (let coin of coins) {
        if (this.isTouching(player, coin)) {
          this.moveCoin(coin);
          score++;
          h1.innerText = score;
        }
      }
    },

这是该函数的调用:

const player = document.querySelector("#player");
const coins = document.querySelectorAll(".coin");
const body = document.querySelector("body");
const h1 = document.querySelector("h1");

const game = makeGameObject();
game.start();

最佳答案

一种方法是动态创建 gameOn() 的绑定(bind)版本并使用它:

{
  // ...

  start() {
    for (let coin of coins) {
      this.moveCoin(coin);
    }
    if (this.boundGameOn === undefined) {
      this.boundGameOn = this.gameOn.bind(this);
    }
    window.addEventListener("keydown", this.boundGameOn)
  },

  stop() {
    window.removeEventListener("keydown", this.boundGameOn);
  },

  // ...
}

理想情况下,您可以在构造函数中执行此操作。如果你有一个构造函数而不是一个对象文字,你可以这样做:

function GameObject () {
  this.boundGameOn = this.gameOn.bind(this)
}

GameObject.prototype = {
  // rest of code ..
}

事实上,在 React 应用程序中,这种设计模式并不罕见:

function GameObject () {
  this.gameOn = this.gameOn.bind(this); // MAGIC!!
}

GameObject.prototype = {
  // ...

  start() {
    for (let coin of coins) {
      this.moveCoin(coin);
    }
    window.addEventListener("keydown", this.gameOn)
  },

  stop() {
    window.removeEventListener("keydown", this.gameOn);
  },

  // ...
}

MAGIC 行确保 gameOn() 内的 this 始终 指向游戏对象,因为您用其自身的绑定(bind)版本覆盖它。

这在 ES6 类语法中看起来稍微干净一些(只是稍微干净一点,我个人对这两种语法都没有偏好):

class GameObject {

  constructor () {
    this.gameOn = this.gameOn.bind(this); // MAGIC!!
  }

  // ...

  start() {
    for (let coin of coins) {
      this.moveCoin(coin);
    }
    window.addEventListener("keydown", this.gameOn)
  }

  stop() {
    window.removeEventListener("keydown", this.gameOn);
  }

  // ...
}

使用 ES7 提出的实验性类属性语法,它甚至更简单:你可以只使用箭头函数(现在,2020 年中期不要直接使用它,因为 Safari 不支持它,但如果你使用 Babel 或 Typescript你可以编译到 ES6):

class GameObject {
  // ...

  start = () => {
    for (let coin of coins) {
      this.moveCoin(coin);
    }
    window.addEventListener("keydown", this.gameOn)
  }

  stop = () => {
    window.removeEventListener("keydown", this.gameOn);
  }

  // ...
}

在本例中,this 由箭头函数绑定(bind)。

关于javascript - 有没有办法使用命名箭头函数来维护对象内的词法范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62256153/

相关文章:

javascript - this.function 不是函数错误,而是函数存在

java - 如何重置Java中的当前对象?

scala - 我如何提供编译时保证我的方法将返回它在 Scala 中获得的相同对象?

javascript - 使用 jquery 刷新表而不与数据库通信

javascript - Node JS - HTML 路径

java - 像数据仓库一样预先计算额外的 Java 对象字段还是即时计算?

javascript - $ ('selector' ) 和 $ ('selector' )[0] 在 jquery 中的区别

javascript - 使用 Reportgrid 作为图形库如何在折线图的数据点处显示图像而不是形状

javascript - 如何使用类名作为预定义变量?

java - 如何调用在不同函数中定义的对象的方法? [安卓]