When working in TypeScript, it's important to note that defining a function using () => {...}
will make the this
variable refer to the instance of the surrounding class. Conversely, using function () {...}
will result in the this
variable maintaining its traditional JavaScript interpretation.
Is there a way to access both versions of the this
variable within a TypeScript function?
This can be particularly handy when utilizing JQuery in TypeScript:
class X {
private v : string;
constructor() {
$('.xyz').on('change', function() {
this.v = $(this).prop('value'); // Two different 'this' contexts
})
}
}
In the highlighted line of code, the first reference to this
should pertain to the class X object, while the second one should relate to the JQuery object that triggered the event.