Is it possible to use this instead of _this?

Topics: General
Dec 22, 2013 at 3:11 PM
In the following example:
{
    Key: 1,
    Elements: [ "1", "2" ],
    toString: () => this.Elements.join(",")
}
It will not work because the lambda expression is trying to get _this (outside) instead of this (inside).

Instead I have to change to
{
    Key: 1,
    Elements: [ "1", "2" ],
    toString: function() { return this.Elements.join(",") }
}
Is there any other way to fix it?

Maybe if TypeScript could also generate self or _self... I don't know what would be the implication of that though.

Should I just use as the last example?
Dec 23, 2013 at 10:48 AM
{
    Key: 1,
    Elements: [ "1", "2" ],
    toString() { return this.Elements.join(",") }
}
Should work :P
Dec 23, 2013 at 4:28 PM
I had no idea this syntax even existed for object literals!
Dec 31, 2013 at 4:29 PM
If you use arrow function expressions, then you are explicitly stating you want 'this' to be a lexically captured 'this', not the usual JavaScript dynamic 'this'. If you still want the regular JavaScript 'this', then use a regular function expression (as you have done). This matches the behavior specified in the next revision of the JavaScript language (ES6).

The final form shown is shorthand for a method in an object literal (which expands to a member with a function expression in the generated code), and is also part of the new syntax coming in ES6 (see http://people.mozilla.org/~jorendorff/es6-draft.html#sec-method-definitions ).
Jan 6, 2014 at 3:28 PM
You could also vote on the feature request for thin-arrow lambdas, a la CoffeeScript, which complement the existing lambdas and do not capture this.