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

1
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 not understand right how to use these functions, in this code I did, is there any way to reference this to Counter without assigning to a variable?

If anyone knows of a good place to learn more about using this and these functions, I'm grateful!

    
asked by anonymous 24.01.2018 / 22:48

2 answers

3
  

... is there any way to reference this to the Counter without assigning to   a variable?

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

  

An arrow function does not have its own this; the value of the enclosing execution context is used

Translating

  

An arrow function does not have this itself; the% used% is that of the context in which it is found.

Here's how:

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 for the function to have its own this . In your case it facilitates.

As for this , bind , and call , the question indicated already enough detail:

    
24.01.2018 / 23:12
2

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

function Contador () {
   this.num = 0;

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

var b = new Contador();

A good article about this you can see this link .

    
25.01.2018 / 00:05