How to access the correct `this` inside a callback with example in JavaScript

Last updated:20th Jan 2023

In JavaScript, when a function is used as a callback, the value of this can be different than what is expected. To ensure that the correct value of this is used inside the callback, there are several ways to access it:

  1. Use the bind() method: The bind() the method creates a new function with the this value bound to the specified object.
let obj = {
  name: 'My object',
  myMethod: function() {
    console.log(this.name);
  }
};

setTimeout(obj.myMethod.bind(obj), 1000); 
  1. Use the call() or apply() method: The call() and apply() methods allow you to explicitly set the value of this inside a function.
let obj = {
  name: 'My object',
  myMethod: function() {
    console.log(this.name);
  }
};

setTimeout(function() {
  obj.myMethod.call(obj);
}, 1000);
  1. Use an arrow function: Arrow functions do not have their own this, they inherit it from the parent scope, so you can use this inside an arrow, function to access the same this as the parent function.
let obj = {
  name: 'My object',
  myMethod: function() {
    setTimeout(() => {
      console.log(this.name);
    }, 1000);
  }
};
obj.myMethod();
  1. Use let that = this inside the outer function and use it inside the callback function.
let obj = {
  name: 'My object',
  myMethod: function() {
    let that = this;
    setTimeout(function(){
      console.log(that.name);
    }, 1000);
  }
};
obj.myMethod();

By using one of these methods, you can ensure that the correct value of this is used inside the callback function.