【问题标题】:How to use global object window or document in javascript es6 Class [closed]如何在javascript es6类中使用全局对象窗口或文档[关闭]
【发布时间】: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 - 我的问题是如何在类中使用documentwindow。我对 this 关键字的用法没有混淆。
  • 看起来你这样做了,因为你错误地使用了.bind,试图访问里面的this。 tl;博士改用箭头函数并删除.bind

标签: javascript dom ecmascript-6 gulp addeventlistener


【解决方案1】:

您不想使用function(){} 进行事件处理,因为常规函数在运行时从上下文派生this,而该上下文不是您的对象,而是全局上下文。使用古老的 bind() 函数(如果操作正确)可以解决这个问题,但现代箭头函数语法也是如此,因此请改用它。

   constructor() {
        console.info('App Initialized');

        document.addEventListener('DOMContentLoaded', () => {
           console.info('document Initialized');
           this.initializeView();
        });
    }

完成。

但是,这是愚蠢的代码,我们根本不需要这样做:在 <head> 元素中加载您的脚本,如 <script src="..." async defer></script>,使用 the defer attribute 以便您的脚本在DOM 已准备好进行查询。它已经存在了大约十年,不需要监听那个事件;只需运行需要运行的代码即可。

   constructor() {
        console.info('App Initialized');
        this.initializeView();
    }

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 2022-11-12
    • 2015-07-02
    • 2023-03-25
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多