by amirdaraee
Posted on 25/06
Normaly in javascript land, when we write a function it comes with it's own this. for instance:
var store = {
name: 'Walmart',
address: '702 S.W. Eighth St., Bentonville, AR 72716',
employees: ['Ben','Sarah','Amir'],
listEmployees: function(){
var storeThis = this;
this.employees.forEach(function(e){
//this.name would return an undefined here so we have to use storeThis.name here
console.log(e + ' works at ' + storeThis.name);
});
}
}
However, in typescript when we write our functions fat arrow style we can use this keyword from the surrounding code because they share the this keyword, so we could write the above example like:
var store = {
name: 'Walmart',
address: '702 S.W. Eighth St., Bentonville, AR 72716',
employees: ['Ben','Sarah','Amir'],
listEmployees: function(){
this.employees.forEach( e => {
console.log(e + ' works at ' + this.name);
});
}
}