How to get the instance itself in a callback?

3
class Cat {
    constructor(name, picture) {    
        this.name = name;
        this.picture = picture;
        this.count = 0;

        // ...

        this.img.click(function () {
            this.count++; // não funciona como eu espero
        });
    }
}

Notice the line this.img.click . From there, this becomes img , but within the callback I manipulate count which is Cat .

I can not use this.count++; as written since this at that point does not refer to Cat anymore.

How do I access the instance of Cat within the callback?

    
asked by anonymous 06.09.2017 / 23:57

2 answers

3

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();
       }
    }

}
    
07.09.2017 / 01:18
2

You can create a reference to the object itself and then use it inside the callback:

class Cat {
    constructor(name, picture) {    
        this.name = name;
        this.picture = picture;
        this.count = 0;

        // ...
        let obj = this; //criar referencia aqui
        this.img.click(function () {
            obj.count++; //usar count através da referencia
        });
    }
}
    
07.09.2017 / 00:08