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

Is there a way to use named arrow function to maintain lexical scope inside an object?

说明: 我正在使用 window.addEventListener() 并想调用命名函数(不是匿名函数),因为我希望能够在稍后阶段使用 removeEventListener .. 但是,eventHandler 中的 console.log 是一个箭头函数,表明 "this" 仍然指向 window 对象而不是游戏对象。

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() 的绑定版本并改用它:

{
  // ...

  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 始终 指向游戏对象,因为您正在用自身的绑定版本覆盖它。

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

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 提出的实验性 class 属性 语法,它甚至更简单:您可以只使用箭头函数(暂时不要直接使用它,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受箭头函数约束。