Javascript

Home Load Console Selectors CSS Form Strings If Else Array Reg Exp Date & Time setTimeout JSON Loops Objects Animation Fat Arrow Class Import IIFE undefined Tabulator.js ES6 Event Listeners AJAX Hide Elements Create Elements Checkbox ejs
O O

Weather Controls

Time Of Day
Rain
Wind Speed
Wind Direction
Clouds

Javascript : Fat Arrow

2022-07-18

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