Should creating a variable named _this conflict with this?
-
13-12-2019 - |
Question
This is a very contrived example, but let's suppose we create a variable _this
somewhere in a class function.
class Person {
constructor (public name : string) {}
changeName(name) {
var _this = {};
(() => {
this.name = name;
})();
}
}
This will not work as expected when we call the changeName
function because the relevant part of the compiled code looks like this:
var _this = this;
var _this = {};
(function () {
_this.name = name;
})();
This is bad Javascript: we have two var
declarations overwriting each other. The _this
created by the compiler is being overwritten by my _this
.
As far as I can see, this behavior isn't specified in the TypeScript spec.
Why should they conflict? Can't the compiler detect if I have created a variable named _this
and name the automatically generated one something else, like _this2
to keep my variables and the compiler-generated ones from trampling on each other?
Solution
The compiler will automatically create _this
as a reference to this
to facilitate the closure that will be created by using lambda syntax. I'm pretty sure I read this in the TypeScript specification somewhere, but I'd agree that the compiler should emit an error in this case.
I don't like the idea of the compiler varying how it emits javascript as this conflicts with the stated goal of generating "idiomatic" (and therefore predictable) javascript.
OTHER TIPS
Isn't it what you would call a reserved variable? I guess you wouldn't declare a variable called "this" or "document" either.
As long as MS is clear as to what the reserved variables are, I don't think there's a major problem. They could perhaps improve the compiler to output warnings though.