首页 > 解决方案 > 调整事件侦听器大小后类方法中断

问题描述

这是我的问题的一个小例子。我正在尝试构建一个响应类,当我更改宽度大小时将调整我的页面。

更改大小后,最初调用的方法会消失。您可以通过调整页面大小自行测试。

class PageManager {
  constructor() {
    this.width;
    this.isMobile;
  }

  init() {
    this.attachListeners();
    this.widthChanges();
    this.adjustPage();
  }

  attachListeners() {
    window.addEventListener("resize", this.widthChanges);
  }

  widthChanges() {
    this.width = window.innerWidth;
    this.adjustPage();
    if (this.width < 491) {
      this.isMobile = true
    } else {
      this.isMobile = false
    }
  }

  adjustPage() {
    console.log("fired");
  }
}

const pageManager = new PageManager();
pageManager.init();

标签: javascript

解决方案


您遇到了范围问题,该功能adjustPage在该功能的范围内不存在widthChanges

当您调用this.adjustPage()函数widthChanges时,this将是函数widthChanges的上下文而不是类 PageManager 的上下文,因此,该函数ajustPage不存在。

您可以解决将类上下文绑定到函数的问题,如下所示。

您可以在此处找到有关此内容的更多信息并进行搜索:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

class PageManager {
  constructor() {
    this.width;
    this.isMobile;
    this.attachListeners = this.attachListeners.bind(this);
    this.widthChanges = this.widthChanges.bind(this);
  }

  init() {
    this.attachListeners();
    this.widthChanges();
    this.adjustPage();
  }

  attachListeners() {
    window.addEventListener("resize", this.widthChanges);
  }

  widthChanges() {
    this.width = window.innerWidth;
    this.adjustPage();
    if (this.width < 491) {
      this.isMobile = true
    } else {
      this.isMobile = false
    }
  }

  adjustPage() {
    console.log("fired");
  }
}

const pageManager = new PageManager();
pageManager.init();


推荐阅读