-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Scope of this is lost when passing a member function to setInterval #10285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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 |
I think TypeScript should still at least print a warning (e.g. "Method passed without instance. Did you mean to use the arrow function? ES6 runtime behavior specifies this, but in most cases, a naive programmer (like me) would expect It took me a while to catch this error because it happened only in specific cases in my code where |
Is this issue still open? I'm happy to work on this! |
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: