... 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?
Would not be
setInterval
? Rsrs– NoobSaibot
@wmsouza No, he wants the
this
ofContador()
rs– Sam
You said in reply: use in the
setTimeout
object b and in the snippet thisthis.timer = setInterval
– NoobSaibot
@wmsouza I meant "inside"... I put the word in the answer to avoid misunderstanding.
– Sam