ES6 in Depth
  • Introduction
  • Installation
  • Block Scope
    • Constant
    • Use cases
  • Template String
    • New String Methods
    • Tagged Template Literal
  • New Number Methods
  • Arrow Function
    • Default Parameters
    • Lexical This Scope
    • Where not to use arrow function
  • Object Enhancement
  • New Array Methods
    • For Of
  • Spread Operator
  • Destructuring
    • Array Destructuring
  • Class
  • Symbols
  • New Data Structures
    • Set
    • Map
    • WeakSet
    • WeakMap
    • Iterators
    • Generators
  • Promise
  • Import Export
Powered by GitBook
On this page
  • this with arraow function referes to parent scope
  • this with ES6 arrow function

Was this helpful?

  1. Arrow Function

Lexical This Scope

// ES5
var obj = {
    name: "Hemant",
    actions: ["Dance", "Sing", "Swim", "Run"],
    displayAction: function(){
        var self = this;
        this.actions.forEach(function(action){
            console.log(self.name + " can "+ action);
        });
    }
}

obj.displayAction();

// OR

var obj = {
    name: "Hemant",
    actions: ["Dance", "Sing", "Swim", "Run", "Eat"],
    displayAction: function(){
        this.actions.forEach(function(action){
            console.log(this.name + " can "+ action);
        }.bind(this));
    }
}

obj.displayAction();

this with arraow function referes to parent scope

var btn = document.querySelector('.btn');

btn.addEventListiner('click', function(){
    console.log(this); // this referes to button clicked on
});

btn.addEventListiner('click', () => {
    console.log(this); // this referes to window
});

btn.addEventListiner('click', function() => {
    console.log(this); // this referes to button

    setTimeout(() => {
        console.log(this); // button, as in arrow function this referes to parent scope 
    })
});

this with ES6 arrow function

var obj = {
    name: "Hemant",
    actions: ["Dance", "Sing", "Swim", "Run"],
    displayAction: function(){
        this.actions.forEach(action => console.log(this.name + " can "+ action));
    }
}

obj.displayAction();
PreviousDefault ParametersNextWhere not to use arrow function

Last updated 4 years ago

Was this helpful?