-
Notifications
You must be signed in to change notification settings - Fork 12.8k
False Sense of Safety When Using “this” Keyword #30073
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
If I understand correctly, probably the option function aaaaa() {
this.z = 1;
}
[1, 2, 3, 4].map(function () { this.x = 0; }) Playground (enable the option under Option button). With that option enabled, flags both See compiler options. You can define the type of this inside a function with that syntax: function aaa(this: { x: number }) {
this.x = 1;
} |
Enabling Here is an example: Calling |
See #513 and start following links from there 😉 |
@RyanCavanaugh I certainly think this issue deserves to remain open as none of the items listed in #513 (or in #7968, #6018 for that matter) is related to what I am proposing here. I am proposing that |
Classes are a JavaScript feature. TypeScript does not alter the runtime behavior of JavaScript, including behavior around |
“
this
” keyword in Javascript is context dependent, which means its value depends on the calling function. And this is one of the culprits of most subtle run-time errors in Javascript.On the other hand, Typescript gives a different meaning to it and uses “
this
” keyword to refer to class properties from inside class methods.But the problem is, when “
this
” is used in callback functions or in functions given to foreach as argument, IDE does not raise any compile-time errors, giving us the false sense of security, but we get run-time errors because “this
” is undefined.There seem to be two work-arounds:
.bind(this)
syntaxI believe that it should not be necessary to use these work-arounds and Typescript should be doing correct static type checking of “
this
” as long as we are not disabling it by using “any
” etc. Because it is the main reason we are using Typescript.I do not have much idea about the inner workings of Typescript, but I assume this could be accomplished by doing a “
let self = this;
” kind of assignment in the transpiling process and using this variable when “this” is used in code.Example code (
obj.fe2()
works whereasobj.fe()
does not)The text was updated successfully, but these errors were encountered: