DEV Community

Suraj Rawat
Suraj Rawat

Posted on

4 ways "this" will be created in Javascript.

Let's say you have a ultra complex 🤣 getUser() function which prints the value of this object in console.

The value of this will change on basis how the function is being invoked with respect to the context.

function getUser() {
  console.log(this);
} 
Enter fullscreen mode Exit fullscreen mode

1. Calling a function with name.

/** "this" holds  window object. **/
getUsers(); 

Enter fullscreen mode Exit fullscreen mode

2. Calling a function with object property.

let someObject = {  
    getUsers: getUsers 
};

/** "this" will be someObject:{}  **/
someObject.getUsers();

Enter fullscreen mode Exit fullscreen mode

3. Calling a function with call, bind & apply methods.

let someObject = {  
    name: "Suraj" 
};

/** "this" will be someObject:{...} **/
getUsers.call(someObject);

Enter fullscreen mode Exit fullscreen mode

4. Calling a function with new keyword.

  /**  "this" will be getUsers {} object **/
  new getUsers();

Enter fullscreen mode Exit fullscreen mode

That's was a short explanation on this creation i know 😃 but that is all you may need to know about this creation for now.

In next blog we'll deep dive into the usage of this.

Top comments (0)