javascript - 调整事件侦听器大小后类方法中断
问题描述
这是我的问题的一个小例子。我正在尝试构建一个响应类,当我更改宽度大小时将调整我的页面。
更改大小后,最初调用的方法会消失。您可以通过调整页面大小自行测试。
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();
解决方案
您遇到了范围问题,该功能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();
推荐阅读
- visual-studio-code - Raspberry Pi 的 Visual Studio Code 是否适用于其他所有人?
- mongodb - Spring Data MongoDB 序列化 Decimal128 不一致的行为
- javascript - Chrome SuppressDifferentOriginSubframeJSDialogs 设置覆盖使用 JS?
- r - 根据模式将元素列表分组到嵌套列表中
- python - 如何根据特定条件将多维数组python中的嵌套列表替换为另一个列表
- jupyter-notebook - 是否可以完全从 Jupyter Notebook 中运行自定义 OpenAI 健身房环境
- javascript - 如何在单个输入中显示数据库中的多个数据
- node.js - Firebase 函数从请求中获取 url 参数
- php - IP 地址详细信息未显示
- javascript - 如何访问嵌套对象然后在 React Native 中渲染它们?