ES6 – “this” on Arrow functions

Hi, today I’m going to show you how the “this” keyword works in an Arrow function.

In Arrow functions, the value of “this” is the same as the value of “this” of the enclosing scope (the global or function scope, inside whichever the Arrow function is defined).

First let’s see how “this” refers in a traditional functions:

// Tradicional function declaration
let myObject = {
  parentFunction: function () {
    console.log("this --parentFunction-->", this); // "this" here is related to myObject { ... }

    let childFunction = function () {
      console.log("this --childFunction-->", this); // "this" here is related to the window
    };

    childFunction(); // "this" here is related to the window

    setTimeout(childFunction, 1000);
  },
};

myObject.parentFunction();

Result:

this” refers in a Arrow functions

So, same example and let’s change to Arrow functions:

// Arrow function declaration
let myObject = {
  parentFunction: () => {
    console.log("this --parentFunction-->", this); // "this" here is related to window

    let childFunction = () => {
      console.log("this --childFunction-->", this); // "this" here is related to the window
    };

    childFunction(); // "this" here is related to the window

    setTimeout(childFunction, 1000);
  },
};

myObject.parentFunction();

Result:

And this is because “this” inside the parentFunction copies the “this” value of the global scope (window), then childFunction copies the “this” value of the parentFunction because is declared inside the parentFunction.

So as I said in the definition: “the value of “this” is the same as the value of “this” of the enclosing scope (the global or function scope, inside whichever the Arrow function is defined). “

By Cristina Rojas.