an abbreviated form of “function”.
let fn = () => {};
Arrow function captures the meaning of this from the surrounding context.
class Person(age) {
this.age = age;
this.growOld = function() {
this.age++;
}
}
var person = new Person(1);
setTimeout(person.growOld,1000);
setTimeout(function() { console.log(person.age); },2000); // 1, should have been 2
this with the function points to window object because window executes the growOld function. So, you got a wrong result.
you will get a right answer using arrow function.
class Person(age) {
this.age = age;
this.growOld = () => {
this.age++;
}
}
var person = new Person(1);
setTimeout(person.growOld,1000);
setTimeout(function() { console.log(person.age); },2000); // 2
Arrow function captures this by creating a new variable _this outside itself. Any execution of this in arrow function basically is executing _this.
The following code explains what arrow function did.
function Person(age) {
this.age = age;
**var _this = this; // capture this**
this.growOld = function() {
_this.age++; // use the captured this
}
}
var person = new Person(1);
setTimeout(person.growOld,1000);
setTimeout(function() { console.log(person.age); },2000); // 2
Note that since you are using TypeScript you can be even sweeter in syntax and combine arrows with classes:
class Person {
**constructor(public age:number) {}**
growOld = () => {
this.age++;
}
}
var person = new Person(1);
setTimeout(person.growOld,1000);
setTimeout(function() { console.log(person.age); },2000); // 2