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

In JavaScript, ‘this’ behaves differently comparing 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



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

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

 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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.