Javascript-类中的窗口调整大小事件使类属性不确定

时间:2019-07-13 11:35:59

标签: javascript oop addeventlistener

我对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()更改为resize(background),然后在调整大小功能中仅使用background this.background中的,在这种情况下,我实际上可以访问背景的属性。但这就像它为我创建了this.background的副本一样,因为我的对象实际上并未调整大小。

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

FWIW,这是从(我简化的)PIXI.js应用程序中获取的。让我知道是否需要包含更多详细信息或从实际的PIXI应用程序中引入一些代码。

0 个答案:

没有答案