how to use bind, call or apply in this context?

Asked

Viewed 56 times

2

function Contador () {
   this.num = 0;
   var obj = this;

     this.timer = setInterval (function add () {
     obj.num++;
     console.log (obj.num);
   }, 1000);
}

var b = new Contador();

I can’t quite understand how to use these functions, in this code I did, there’s some way to reference the this Counter without assigning to a variable ?

If anyone knows of any good place to learn more about the use of this and these functions, I am grateful!

2 answers

5


... has some way of referencing this to Counter without assigning to a variable ?

Yes, using a Arrow Function instead of a normal function. Read in the documentation will see that the Arrow Function does not change the this:

An Arrow Function does not have its Own this; the this value of the enclosing Execution context is used

Translating

An Arrow Function does not have its own this; the this used is the context in which it lies.

See how it looks:

function Contador () {
   this.num = 0;

   this.timer = setInterval (() => { //arrow function aqui
     this.num++; //this aqui refere Contador
     console.log (this.num); //e aqui também
   }, 1000);
}

var b = new Contador();

There are cases where this behavior becomes a disadvantage, when it is necessary that the function has its own this. In your case you end up facilitating.

As to the bind, call and apply the question already indicated enough detail:

What’s the difference between apply, call and bind methods when calling a function in Javascript?

2

The function Contador() was assigned to the object b, use inside the setTimeout the object b representing that function. The effect will be the same as the this of the scope of the function Contador():

function Contador () {
   this.num = 0;

     this.timer = setInterval (function add () {
     b.num++;
     console.log (b.num);
   }, 1000);
}

var b = new Contador();

A good article on the this you can see at this link.

  • Would not be setInterval ? Rsrs

  • @wmsouza No, he wants the this of Contador() rs

  • You said in reply: use in the setTimeout object b and in the snippet this this.timer = setInterval

  • @wmsouza I meant "inside"... I put the word in the answer to avoid misunderstanding.

Browser other questions tagged

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