Scope of this is lost when passing a member function to setInterval #10285
Comments
Thanks @RyanCavanaugh, still should be either caught at the compile stage (which is possible if it's expected behaviour) and flagged as a warning, or the generated JS structured should generate the obvious intent. |
See "something about You can have the "correct" code generated by using an arrow function: private setIntervalCallback = () => {
console.log(this.someNumber);
}; |
Also, note that this behaviour is consistent with the ES6 runtime behaviour. Methods are not statically bound to the instance. |
There are two parts to get this working correctelly:
declare function setInterval(handler: (this: void, ...args: any[]) => void, timeout: number): number;
|
I would say the change to the library should be done either ways. |
I think here TypeScript should keep the same semantics just as ES6, but not force it bound by default. |
setInterval(()=>this.setIntervalCallback(), 400); should be just working fine so that the callback can see |
TypeScript Version: 1.8.10
When passing a member function to setInterval, the scope of 'this' is lost within the callback, though the structure of the code (given experience of any object orientated language) indicates it shouldn't be.
Example code
Expected behavior
When console.log(this.someNumber); is called, the scope of this is within the scope of the SetIntervalTest interval instance, printing '1'.
Actual behavior:
The scope of this is pulled from global scope, resulting in this.someNumber being 'undefined'. If that isn't possible, the compiler should indicate the expected behaviour is not what you're going to get.
To fix this i need to change 'setInterval(this.setIntervalCallback, 400);' to 'setInterval(() => this.setIntervalCallback(), 400);' so 'this' is correctly scoped in the callback.
The text was updated successfully, but these errors were encountered: