1

我有一个类名对话框。在这个类中,我有一个方法 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();
    }
}
4

3 回答 3

1

Javascriptsthis上下文在事件侦听器中发生变化。您可以通过将 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 访问类上下文。

于 2020-07-20T13:55:06.337 回答
0

我认为这应该对你有用

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

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

于 2020-07-20T13:55:53.373 回答
0

如果您使用的是 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();
    }
}````
于 2020-07-20T13:58:05.067 回答