Can I access the other this in a TypeScript lambda?

You would need to avoid the fat-arrow syntax to do this as you don’t want to preserve the lexical scope of this.

var _me = this;
$('#something').fadeOut(400, function () {
    _me.invokeAnotherMethod();
    $(this).data('specialhide', true);
});

In this example I have used _me rather than _this to avoid any collisions with TypeScript generated variables. I have also avoided self, to avoid confusion with window.self (thanks RockResolve).

The Why!

The ECMAScript 6 specification features Arrow Function Definitions – it is where the TypeScript language has taken this feature from. When TypeScript targets ECMAScript 6 in the future, it will leave in the () => syntax – so they can’t make it work with both contexts of this without breaking future compatibility.

Even though you could imagine how they could change the TypeScript compiler to make both _this and this available in ECMAScript 3 or 5, it would actually become a problem in version 6.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)