In TypeScript, when you use the () => syntax, it actually just creates a variable to contain the "current meaning of this" and then substitutes usages of this to call the generated variable. You can do this manually in situations where you want both meanings of this.
Here are some examples...
Normal use of this in a callback. this is the event target.
$('div').click( function () {
// this is the clicked element
alert('this: ' + this.id);
});
TypeScript arrow function used for a callback. this is the lexical scope.
$('div').click( () => {
// this is the lexical scope
// i.e. the containing class, containing function, or window
alert('this: ' + this.id);
});
Manual example, creating a variable named self to contain the lexical scope and leaving this to be the event target.
var self = this;
$('div').click( function () {
// this is the clicked element
alert('this: ' + this.id);
// self is the lexical scope
// i.e. the containing class, containing function, or window
alert('self: ' + self.id);
});
It is worth bearing in mind that JavaScript walks the scope chain at runtime, so if a variable isn't defined inside of a function, JavaScript inspects the enclosing function for the variable. It keeps walking up the chain until it has checked the global scope.
This example shows this in action, but the nesting can be much deeper and it still works (i.e. a function inside of innerFunction can still scope-walk to get to the test variable.
var example = function () {
var test = 'A test';
var innerFunction = function () {
alert(test); // 'A test'
}
innerFunction();
}
example();