1

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?

Harry
  • 521
  • 7
  • 21
John Cadac
  • 89
  • 1
  • 11
  • 2
    Inside the event listener, `this` refers to the element that fired the event, not your class instance. I'm sure there is a dupe for this on SO – ibrahim mahrir Dec 12 '18 at 17:52

2 Answers2

2

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();
   }
}
Mark
  • 90,562
  • 7
  • 108
  • 148
1
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();
        }.bind(this)

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

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

As was pointed out by @ibrahim mahrir, you lose the context of this inside the event listener. bind explicitly sets the this value to whatever you give it as a parameter.

richbai90
  • 4,994
  • 4
  • 50
  • 85