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

描述: 我正在使用并希望调用一个命名函数(不是匿名函数),因为我希望能够在以后的阶段使用 removeEventListener。但是,事件处理程序(即箭头函数)的内部显示“this”仍指向窗口对象而不是游戏对象。window.addEventListener()console.log


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


郎朗坤
浏览 109回答 1
1回答

牛魔王的故事

一种方法是动态创建 的绑定版本并改用它: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 行确保内部始终指向游戏对象,因为您正在用其自身的绑定版本覆盖它。thisgameOn()这在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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript