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?