2

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?

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 2
    This seems like a pretty serious issue to me. It should be at least covered in the language spec. I'd recommend posting this on [the TypeScript issue tracker](http://typescript.codeplex.com/workitem/list/basic) for an official response. – joshuapoehls Oct 03 '12 at 14:14

2 Answers2

7

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.

x0n
  • 51,312
  • 7
  • 89
  • 111
0

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.

laurent
  • 88,262
  • 77
  • 290
  • 428
  • 1
    It's not documented as a reserved variable, as far as I can see. It doesn't output any warnings or errors. – Peter Olson Oct 03 '12 at 14:28
  • Likewise, there's nothing in JavaScript to keep you from declaring a variable named `document`. However, in a browser environment, `document` will exist as a host variable and you won't be able to reassign it. – Jason Suárez Oct 04 '12 at 08:14