Search code examples
javascriptjavascript-objects

calling function from constructor inside class


I created the following class:

class GlobalModal {
    constructor(text) {
        this.modal = document.getElementById('Modal');
        this.span = document.getElementById("closeModal");
        this.text = text;

        //Show the GlobalModal
        this.modal.style.display = "block";

        // When the user clicks on <span> (x), close the modal
        this.span.onclick = function() {
            this.close();
        }

        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == this.modal) {
                this.close();
            }
        }
    }

    // Function to close the GlobalModal
    close() {
        this.modal.style.display = "none";
    }
}

I'm trying to call the function this.close();

Error: this, close is not a function.

Is what I'm trying to do even possible? What am I doing wrong?


Solution

  • If you want to use this in the callback you should use an arrow function which binds this to the lexical context:

    window.onclick = (event) => {
       if (event.target == this.modal) {
          this.close();
       }
    }