Arrow Functions

With arrow functions, we can manipulate the 'this' keyword.

Fat arrow function make use of 'Lexical this'

Problem before Arrow functions:

var person = {
    firstName : "Nelson", 
    printNameDelayed: function(){
        window.setTimeout(function(){
            //The 'this' is not the this that is associated with this person. 
            //Will print 'undefined'
            console.log(this.firstName); 
        },1000);
    }
};
person.printNameDelayed();

//Potential solution: 
//Using bind: 
var person = {
    firstName : "Nelson", 
    printNameDelayed: function(){
        window.setTimeout((function(){
            console.log(this.firstName); 
        }).bind(this),1000);
    }
};

//Using alias:
var person = {
    firstName : "Nelson", 
    printNameDelayed: function(){
        var that = this; 
        window.setTimeout(function(){
            console.log(that.firstName); 
        },1000);
    }
};

Solution:

var person = {
    firstName : "Nelson", 
    printNameDelayed: function(){
        window.setTimeout(() => {
            console.log(this.firstName); 
        },1000);
    }
};

person.printNameDelayed();

The fat arrow function, we can think of it as equivalent to binding this callback to the lexically scoped 'this' in the function above it. The 'this' carries forward, even if we nest function.

Other Example:

var myFunction = () => console.log("Hello, World");
myFunction();

var myFunction2 = () => {
    console.log("Whoa"); 
}

var myFunction3 = arg => {
    console.log(arg); 
}
myFunction3(10);

More:

//Example 1:
const add = function(a,b) {
    return a + b; 
}

const add = (a,b) => {
    return a + b;
}

//Implicit return if we only have one expression: 
const add = (a,b) => a + b;

More on solving 'this'

//ES5 problem: 
const team = {
    members: ['Jane', 'Bill'],
    teamName : 'Super Squad',
    teamSummary : function() {
        return this.members.map(function(member){
            return `${member} is on team ${this.teamName}`
        }); 
    }
};

console.log(team.teamSummary()); -> ["Jane is on team undefined", "Bill is on team undefined"] 
//The value of 'this' is lost, we could use the .bind(this); 

//Bind solution: 
const team = {
    members: ['Jane', 'Bill'],
    teamName : 'Super Squad',
    teamSummary : function() {
        return this.members.map(function(member){
            return `${member} is on team ${this.teamName}`
        }).bind(this); //Bind the function context(function(member).....) to the current context which means when we invoke the this.teamName, it will be correct
    }
};

//ES6 Solution
const team = {
    members: ['Jane', 'Bill'],
    teamName : 'Super Squad',
    teamSummary : function() {
        return this.members.map(member => {
            return `${member} is on team ${this.teamName}`
        }); 
    }
};

console.log(team.teamSummary()); -> ["Jane is on team Super Squad", "Bill is on team Super Squad"]

results matching ""

    No results matching ""