类方法在调整事件侦听器大小后中断



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

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

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的作用域下。

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

您可以解决将类上下文绑定到函数中的问题,就像下面这样。

你可以在这里找到更多关于这个和scrope的信息: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();

addEventListener的回调调用时,添加事件的对象(在本例中为窗口(绑定为this。您可以使用箭头函数,也可以自己绑定this值。

window.addEventListener("resize", this.widthChanges.bind(this));
//or
window.addEventListener("resize", ()=>this.widthChanges());

最新更新