【发布时间】:2021-12-01 13:44:52
【问题描述】:
如何在 JavaScript ES6 类中使用窗口或文档
我尝试了以下代码
场景 #1:
class App {
constructor() {
console.info('App Initialized');
document.addEventListener('DOMContentLoaded', function() {
console.info('document Initialized');
this.initializeView();
}).bind(this);
}
initializeView() {
console.info('View Initialized');
}
}
const app = new App();
注意:我使用gulp js
编译了上面的代码如果我尝试调用document.addEventListener 中的类方法,则会引发以下错误。
Uncaught TypeError: this.initializeView is not a function
所以,我将this 对象绑定到文档.bind(this)
场景 #2:
class App {
constructor() {
console.info('App Initialized');
document.addEventListener('DOMContentLoaded', function() {
console.info('document Initialized');
}).bind(this);
}
}
const app = new App();
如果我尝试不使用 document.addEventListener,它会在浏览器中按预期工作,但如果我尝试使用 document.addEventListener,则会引发错误
Uncaught TypeError: document.addEventListener(...) is undefined
请帮助我如何使用 es6 类中的窗口或文档。
场景#3:
class Booking {
stepper = 1;
constructor() {
console.info('Booking Initialized');
document.addEventListener('DOMContentLoaded', function() {
console.log('document Initialized')
});
}
}
我收到以下异常
Uncaught ReferenceError: options is not defined
提到的解决方案与问题的没有任何相关性 题材 How to access the correct `this` inside a callback
我不确定提供上述链接的专业知识如何 解决方案。
【问题讨论】:
-
document.addEventListener(...).bind(this)毫无意义。删除.bind(this)。 -
@CertainPerformance - 我详细阐述了这个问题,还提到了为什么我使用
.bind(this)请帮助我如何运行代码,没有任何异常。 -
@CertainPerformance - 我的问题是如何在类中使用
document或window。我对this关键字的用法没有混淆。 -
看起来你这样做了,因为你错误地使用了
.bind,试图访问里面的this。 tl;博士改用箭头函数并删除.bind
标签: javascript dom ecmascript-6 gulp addeventlistener