Saturday, December 13, 2025
HomeLanguagesJavascriptHow to access the correct `this` inside a callback?

How to access the correct `this` inside a callback?

In JavaScript, ‘this’ behaves differently compared to other programming languages. If we are performing a normal function call then ‘this’ points to the window object. But we are calling the function differently than ‘this’ will point to a near object. To understand it better below we elaborated with two code snippets with two different call approaches.

Example 1: When we call a function in a normal way in the below example

Javascript




function printThis(){
  
  console.log(this);
  
}
  
printThis();


Output:

Window {0: Window, window: Window, 
        self: Window, document: document, 
        name: '', location: Location, …}

Example 2: When we call a function using object notation.

Javascript




var obj={
 name: "Ramesh",
 printThis: function(){
    console.log(this);
 }
}
obj.printThis();


Output:

{name: 'Ramesh', printThis: ƒ}

So, from the above two examples, we can clearly understand the behavior of ‘this’ when we make different types of function calls. 

Approach: First create an object and enter sample properties. Make sure you add a function for one key, in that function add a callback function using setTimeout. Inside this setTimeout function use ‘bind’ to bind the context of this after then return this.

Example: Using Bind

Javascript




var outerFunction= function(){
   innerFunction = function() {
   };
    setTimeout(innerFunction.bind(this),2000);
     return this;
};
  
var obj = { method: outerFunction ,company :'neveropen'} ;
obj.method();


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7200 POSTS0 COMMENTS
Thapelo Manthata
6897 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS