Skip to content

Allow captured this in a class #1859

Closed
Closed
@nycdotnet

Description

@nycdotnet

It's common for JavaScript code to capture this to a variable like self or that. One of the pain points when converting existing JavaScript functional-style "class" code to an idiomatic TypeScript class is the required chore of going through the file and replacing any instance of a captured this variable with an ambiguous this, likely breaking code that was already working; then, doing a second pass to figure out which functions need to be converted to lambdas to hopefully unbreak the code. This chore is tedious, error prone, and offers no business value; in fact it has a negative value at first. It's also a "day 1 sledgehammer" - the very people who are most likely to need to do this type of work are JavaScript developers giving TypeScript a try.

I think there's a very straight-forward solution for this: it should be legal to capture this at the top of a TypeScript class. For example:

class MyClass {
  var that = this;
  public name: string;
  public sayHello() {
    console.log(that.name);
  }
}

proposed emit:

var MyClass = (function () {
    function MyClass() {
        var that = this;
        this.sayHello = function () {
            console.log(that.name);
        };
    }
    return MyClass;
})();

The emit would work identically to how the automatic var _this = this; works when lambdas are used in a class. In the example above, that would be of type MyClass. I don't believe that it would be required to support this proposal in a defintion file except perhaps when typeof is used, in which case the name of the class could be substituted for the typeof expression. Multiple variables could plausibly be assigned to this, but it would remain illegal to declare variables in the class scope unless they are immediately assigned to this; the emit would have to be at the top of the function, above member definitions (same place as var _this = this; already is).

Having this feature would save a tremendous amount of busywork when converting large classes from JavaScript to TypeScript. I know there are a bunch of other this proposals out there, but I read through #513 and it didn't seem to have this particular idea.

Thanks very much for your efforts with TypeScript - it's such a great language to work with. I appreciate your consideration of this proposal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions