javascript - 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 应用程序中引入一些代码,请告诉我。
解决方案
推荐阅读
- android - 向所有应用用户发送短信 - 如何?
- c++ - 如何使用 Bullet Physics SDK 清除 VS2015 中的错误 LNK2001?
- c++ - 给定描述使用什么数据类型?
- google-apps-script - 无法从表格插件创建 onFormSubmit 触发器
- python - 无法解析使用 rest api 返回的 xml 响应
- jmeter - 无法在 jmeter 5.1 上录制脚本
- c++ - 获取最后 5 个数组对象 C++
- firebase - 如何阅读 Firebase 文档
- jquery - 附加 HTML 后如何在点击事件中检测 id
- c - 不使用返回值调用函数有什么影响?