JavaScript this keyword in Arrow Function

Arrow function does not have its own this.

Whenever you call this, it refers to its parent scope.

Inside a regular function, this keyword refers to the function where it is called.

With arrow functions the this keyword always represents the object that defined the arrow function.

this represents an object that executes the current function. 

Example

Inside a regular function

function Person() {
    this.name = 'Jack',
    this.age = 25,
    this.sayName = function () {

        // this is accessible
        console.log(this.age);

        function innerFunc() {

            // this refers to the global object
            console.log(this.age);
            console.log(this);
        }

        innerFunc();

    }
}

let x = new Person();
x.sayName();
Output
  • Here, In above example this.age inside this.sayName() is accessible because this.sayName() is the method of an object.
  • However, innerFunc() is a normal function and this.age is not accessible because this refers to the global object (Window object in the browser).
  • Therefore, this.age inside the innerFunc() function gives undefined.

Inside an arrow function

function Person() {
    this.name = 'Jack',
    this.age = 25,
    this.sayName = function () {

        console.log(this.age);
        let innerFunc = () => {
            console.log(this.age);
        }

        innerFunc();
    }
}

const x = new Person();
x.sayName();
Output
  • Here in above example, the innerFunc() function is defined using the arrow function.
  • Inside the arrow function, this refers to the parent’s scope.
  • Therefore, this.age gives 25.