There are 4 ways to do this.
1. Save a variable reference
The first is that of isac response, and consists of keeping a reference to the object this
desired in a variable to which the function has access. I repeat the example of Isac:
let obj = this; //criar referencia aqui
this.img.click(function () {
obj.count++; //usar count através da referencia
});
2. Create a function with this
fixed
Every function in JS has a method bind
which creates a copy of the function attached to a this
specific. With this feature you could do so:
const incrementar = function() {
this.count++
};
this.img.click(incrementar.bind(this));
3. Arrow functions
As Arrow functions have no context/this
own, and allow something closer to its original code:
this.img.click( () => this.count++ );
4. Implementing EventListener
This method is little known, but its object can listen to and treat events internally if it implements the interface EventListener
. An example based on your:
class MyCounter {
constructor() {
this.count = 0;
this.btn = document.querySelector('#some-button');
// Repare que passamos this em vez de uma função
this.btn.addEventListener('click', this, false);
}
incrementa() {
this.count++;
}
// Implementa a interface EventListener
handleEvent(e) {
if(e.type === 'click') {
this.incrementa();
}
}
}