How to get the instance itself (this) in a callback?

Asked

Viewed 77 times

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

Watch the line this.img.click. From it, the this becomes the img, but inside the callback I manipulate the count that is of Cat.

I can’t use this.count++; as it is written this at that point no longer refers to Cat.

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

2 answers

3


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

}

2

You can create a reference to the object itself that you then use 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
        });
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.