简体   繁体   中英

Accessing class method inside eventListener function Javascript

I have a Class names dialog. Inside this class I have a method hide() to hide the dialog box itself and its modal box. But I can't access hide function from "onclick" function. How can I access it?

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();
    }
}

Javascripts this context changes inside event listeners. You can work around this by adding the this context to a seperate variable:

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();
    }
}

As you can see I assign the this context to the variable self . After that you can access the class context with self.

I think this should work for you

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

Context of this is different in event listener so you should bind your actual this to eventListener context

Change the onclick function's listener to arrow function if you are using es6+.. arrow functions don't override 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();
    }
}````

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM