Skip to content
Related Articles

Related Articles

How to access the correct `this` inside a callback?
  • Last Updated : 01 Oct, 2020

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




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

Output:



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

Javascript




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

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




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

My Personal Notes arrow_drop_up
Recommended Articles
Page :