How to Get 'Object this' Inside an Arrow Function in JavaScript
Adam C. |

In an arrow function, the this keyword behaves differently than in a regular function. In an arrow function, the this keyword is lexically scoped, meaning that it takes its value from the enclosing execution context. This is in contrast to regular functions, where the value of this is determined by how the function is called.

If you've read my previous blog post, Understanding the 'this' Keyword in JavaScript: Anonymous Functions vs Arrow Functions, you may already be familiar with the differences between 'this' in arrow functions and regular functions. However, what if you find yourself needing to access the value of 'this' from the enclosing execution context within an arrow function?

Photo by Olav Ahrens Røtne on Unsplash

Here are two solutions:

Solution 1

Capture the this value in a variable outside the arrow function, and then use that variable inside the arrow function, like this:

function myFunction() {
  const self = this;
  setTimeout(() => {
    console.log("This is the 'this' value:", self);
  }, 1000);
}

Here, the self variable is assigned the value of this outside the arrow function, and then used inside the arrow function to access the same value.

Solution 2

Use the bind method to explicitly bind the this value to the arrow function, like this:

function myFunction() {
  setTimeout(() => {
    console.log("This is the 'this' value:", this);
  }.bind(this), 1000);
}

Here, the bind method is used to bind the value of this to the arrow function at the time of creation. This ensures that the arrow function will always use the same this value as the enclosing execution context.