In typescript, I can write something like this:
$('#something').fadeOut(400, (): void => {
this.invokeAnotherMethod();
});
When compiled, TypeScript automatically makes sure this points to my class instead of the enclosed function:
var _this = this;
$('#something').fadeOut(400, function() {
_this.invokeAnotherMethod();
});
However, what about when I need to access the real this instead of the outer _this? Is there syntax to reference it? For example, how could I write code that would compile to the following:
var _this = this;
$('#something').fadeOut(400, function() {
$(this).data('specialhide', true);
_this.invokeAnotherMethod();
});
Is it possible?
You would need to avoid the fat-arrow syntax to do this as you don’t want to preserve the lexical scope of
this.In this example I have used
_merather than_thisto avoid any collisions with TypeScript generated variables. I have also avoidedself, to avoid confusion withwindow.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 ofthiswithout breaking future compatibility.Even though you could imagine how they could change the TypeScript compiler to make both
_thisandthisavailable in ECMAScript 3 or 5, it would actually become a problem in version 6.