Javascript : Fat Arrow
Overview
The Fat Arrow (aka Arrow Function) is a new feature is ES6.
=>
Problem 1
Vanilla JS Problem
Here we have this.age++ pointing to window, which will make this not work as desired.
function 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
Vanilla JS Solution
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
Fat Arrow Solution
function 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
Reference
https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html