I wrote the following code, thinking it wouldn´t really work (I didn´t expect reset to be able to access this.Interval in order to clear it). But to my surprise, it worked.
How could that be though? Doesn´t the this prevent that from happening (doesn´t it bind Interval to the method and makes it inaccesible to the other scopes)?
I can’t see where Interval is declared.
In the HandleTimer, second part of the snippet.
this has different behaviors, depends on how you call the function.
When you use this into a method, this will refer to the object.
e.g.: bar.foo();
this will refer to bar, not to foo.
See here more about this -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method
If you want something on the method scope you have to use let
e.g.: let interval = setInterval(() => { ...
Extra:
If you use this into a normal function, it will refer to global scope
Try this:
function foo(){
console.log(this); // will log your global scope
}
You can change the way it works on the function using strict mode:
function foo() {
'use strict';
return this;
}
console.log(foo()); //undefined