【问题标题】:Accessing class method inside eventListener function Javascript访问eventListener函数Javascript中的类方法
【发布时间】:2020-11-09 19:03:33
【问题描述】:

我有一个类名对话框。在这个类中,我有一个方法 hide() 来隐藏对话框本身及其模式框。但我无法从“onclick”功能访问隐藏功能。如何访问它?

class Dialog{
    constructor(id){
        this._dialogBox = $('.dialog#'+this.id);
        this._closeButton = this._dialogBox.find('span.closedialog');

        this._closeButton.on('click', function(){
            //how to access hide() function from here?
        });

    }
    hide(){
        this._dialogBack.hide();
        this.dialogBox.hide();
    }
}

【问题讨论】:

  • 与问题无关我不禁注意到将span.closedialog 更改为button.closedialog (在HTML 中)可能是一个好主意。这改进了 HTML 语义,并为可用性和可访问性带来了显着的好处。尝试仅使用键盘 TAB 键聚焦 SPAN...如果使用正确的语义,所有这些都是免费的

标签: javascript class object this this-keyword


【解决方案1】:

Javascripts this 事件监听器内部的上下文变化。您可以通过将 this 上下文添加到单独的变量来解决此问题:

class Dialog{
    constructor(id){
        this._dialogBox = $('.dialog#'+this.id);
        this._closeButton = this._dialogBox.find('span.closedialog');

        const self = this;

        this._closeButton.on('click', function(){
            //how to access hide() function from here?
            self.hide()
        });

    }
    hide(){
        this._dialogBack.hide();
        this.dialogBox.hide();
    }
}

如您所见,我将this 上下文分配给变量self。之后,您可以使用 self 访问类上下文。

【讨论】:

    【解决方案2】:

    我认为这应该适合你

    this._closeButton.on('click', this.hide.bind(this));
    

    事件侦听器的上下文不同,因此您应该将实际的 this 绑定到 eventListener 上下文

    【讨论】:

      【解决方案3】:

      如果您使用的是 es6+,请将 onclick 函数的侦听器更改为箭头函数。箭头函数不会覆盖 this

      class Dialog{
          constructor(id){
              this._dialogBox = $('.dialog#'+this.id);
              this._closeButton = this._dialogBox.find('span.closedialog');
      
              this._closeButton.on('click', () => {
                 this.hide();
              });
      
          }
          hide(){
              this._dialogBack.hide();
              this.dialogBox.hide();
          }
      }````
      

      【讨论】:

        猜你喜欢
        • 2022-06-13
        • 2014-11-26
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多