0

I have a class and in this class I have an event listener with a callback method.

In the callback method, this will refer to the listener element.

How can i get this refer to my class ?

class Myclass {
 constructor() {
  console.log(this); // Here this return Myclass
  window.addEventListener('click', this.clickListener, false);
 }
 clickListener(e) {
  console.log(this); // Here this return window 
 }
}

var myClass = new Myclass();
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
Ben
  • 1
  • Does this answer your question? ["This" within es6 class method](https://stackoverflow.com/questions/36489579/this-within-es6-class-method) – Laszlo Mar 22 '20 at 14:22

1 Answers1

0

you can use an arrow function or bind.

class Myclass {
    constructor() {
        console.log(this); // Here this return Myclass
        window.addEventListener('click', () => {
          this.clickListener();
        });
        
        // with bind window.addEventListener('click', this.clickListener.bind(this), false);
    }
    clickListener(e) {
        console.log(this); // Here this return window 
    }
}

var myClass = new Myclass();
J. Langer
  • 128
  • 12