I was stuck in some weird problem and then the problem got a challenge to understand why Angular behaves like this, there was no much luck searching at Google for the problem, so I am here.
I wanted to test setInterval()
function and counter some variable, not something too hard, and I got stuck in problem that I couldn't find solution for or explaination.
This is my code I am using and it works fine:
public counter: number = 1;
myFunction() {
setInterval(() => {
console.log(this.counter);
this.counter++;
}, 1000);
}
Output: 1, 2, 3, 4, 5...
This code works fine, but when I am taking the function to be like this, I get undefined as output and then Nan, Nan, Nan
.
public counter: number = 1;
foo() {
console.log(this.counter);
this.counter++;
}
myFunction() {
setInterval(this.foo, 1000);
}
* myFunction is the starting function *
Output: undefined, Nan, Nan, Nan...
I guess there is some problem with variables access that foo() cannot access the global variables, but how is that happening? and how can I fix this problem?