首页 > 解决方案 > Javascript - 类中的窗口调整大小事件使类属性未定义

问题描述

我对 OOP 原则很不了解,所以这对我来说很难解释,但是就这样吧。

我想要做的是将“window.resize”事件处理程序移动到一个类中,并让从所述类实例化的任何对象处理它自己的大小调整,但问题是当我将处理程序移动到类中时,并且处理程序然后触发,对象似乎无法访问它自己的属性 - 它们的全部undefined

让我向您展示我正在尝试做的事情。

我当前的(工作)代码:

// index.js
window.addEventListener('resize', resize);

let thing;
function setup() {
    thing = new CustomThing();
}

function resize() {
    thing.resize();
}

setup();


// CustomThing.js
class CustomThing {
    constructor() {
        this.background = { width:100, height:100 };
    }

    resize() {
        console.log('I\'m successfully resizing. Yay!');
        this.background.width = window.innerWidth;
    }
}

我正在尝试将上面的代码转换为以下内容:

// index.js
let thing;
function setup() {
    thing = new CustomThing();
}
setup();
// Notice that I don't have the event listener or resize function here anymore


// CustomThing.js
class CustomThing {
    constructor() {
        this.background = { width:100, height:100 };
        window.addEventListener('resize', this.resize);
    }

    resize() {
        console.log('this.background is now undefined :(');
        this.background.width = window.innerWidth;
    }
}

我还尝试将上面的内容更改window.addEventListener('resize', this.resize);window.addEventListener('resize', () => this.resize(this.background));, 和resize()into resize(background),然后仅background在 resize 函数中使用而不是this.background,在这种情况下我实际上可以访问背景的属性。但是,就好像它创建了一个副本this.background供我操作,因为我的对象实际上并没有调整大小。

所以我的问题是:如何重构下面的代码,以便我可以在我的类中拥有 resize 事件处理程序,在它触发时调用一个函数,然后从被调用的函数中成功访问类的其他属性?

FWIW,这是从我正在处理的 PIXI.js 应用程序中获取(并简化)的。如果我需要包含更多详细信息或从我的实际 PIXI 应用程序中引入一些代码,请告诉我。

标签: javascriptoopaddeventlistener

解决方案


推荐阅读