There are 4 ways to do this.
1. Save a reference in variable
The first is Isac's response , and is to save a reference to the desired this
object in a variable that the function has access to. I repeat the Isac example:
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
that creates a copy of the function tied to a specific this
. With this feature you could do this:
const incrementar = function() {
this.count++
};
this.img.click(incrementar.bind(this));
3. Arrow functions
The arrow functions does not have context /
this
itself, 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 and treat events internally, if implemented at 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();
}
}
}