top

Understanding the “this” Keyword in JavaScript

In this article, we are going to learn about Javascript keyword “this” and how the value of “this” is assigned in different scenarios. The best way to digest the content of this article is by quickly executing the code snippet in browser’s console. Follow below steps to launch console in Chrome browser: Open new tab in chrome Right click on page and select “inspect element” from context menu Go to the console panel Start executing Javascript code Objects are the basic building blocks in Javascript. There is one special object available in Javascript, “this” object. You can see the value of “this” at every line of Javascript execution. The value of “this” is decided based on how the code is being executed. Before getting started about “this”, we need to understand a little about Javascript runtime environment and how a Javascript code is executed. Javascript Interpreter and Execution Context Javascript is a scripting language which means that there is no compilation step in code execution. Interpreter reads the code and executes it line by line. The environment (or scope) in which the line is being executed is know as “Execution Context”. The Javascript runtime maintains a stack of these execution contexts and the execution context present at the top of this stack is currently being executed. The object that “this” refers changes every time execution context is changed. “this” refers to global object By default, the execution context for an execution is global which means that if a code is being executed as part of a simple function call then “this” refers to global object. “window” object is the global object in case of browser and in Node.JS environment, a special object “global” will be the value of “this”. For example: Immediately Invoked Function Expression (IIFE)   Note: If the strict mode is enabled for any function then the value of this will be “undefined” as in strict mode, global object refers to undefined in place of windows object. For Example:   “this” refers to new instance When a function is invoked with “new” keyword then the function is known as constructor function and returns a new instance. In such cases, the value of “this” refers to newly created instance. For Example: In case of person.displayName, “this” refers to new instance person and in case of person2.displayName(), “this” refers to person2 which is a different instance of Person. “this” refers to invoker object (parent object) In Javascript, property of an object can be a method or a simple value. When an Object’s method is invoked, “this” refers to the object which contains the method being invoked. In this example, we are going to use method foo defined in first example. By above example, it is clear that how value of “this” can be confusing in some cases. The function definition of foo1 is same but when it is being called as a simple function call then “this” refers to global object and when same definition is invoked as an object’s method then this refers to the parent object. So the value of “this” depends on how a method is being invoked as well. “this” with call, apply methods A function in javascript is also a special type of object. Every function has call, bind and apply methods. These methods can be used to set custom value of “this” to the execution context of function. We are going to use the second example defined above to explain the use of call: The only difference between call and apply method is the way argument is passed. In case of apply, second argument is an array of arguments where in case of call method, arguments are passed individually.   “this” with bind method bind method returns a new method with “this” refers to the first argument passed. We are going to use above example to explain bind method. “this” with fat arrow function As part of ES6, there is a new way introduced to define a function. let displayName = (fn, ln) => {     console.log(Name: ${fn} ${ln}); }; When a fat arrow is used then it doesn’t create a new value for “this”.  “this” keeps on referring to the same object it is referring, outside the function. Let’s look into some more examples to test our knowledge about “this” Since the callback is invoked as a simple function call inside multiple function, “this” refers to global object windows inside execution context of callback method. Summary     So now, you can figure out the value of “this” by following these simple rules:     By default, “this” refers to global object which is global in case of NodeJS and windows object in case of browser When a method is called as a property of object, then “this” refers to the parent object When a function is called with “new” operator then “this” refers to the newly created instance. When a function is called using call and apply method then “this” refers to the value passed as first argument of call or apply method. As you have seen above, the value of “this” can sometimes be confusing but above rules can help you to figure out the reasoning of the value of “this”.  
Rated 4.0/5 based on 20 customer reviews
Normal Mode Dark Mode

Understanding the “this” Keyword in JavaScript

Pavan Kumar
Blog
11th Jan, 2018
Understanding the “this” Keyword in JavaScript

In this article, we are going to learn about Javascript keyword “this” and how the value of “this” is assigned in different scenarios. The best way to digest the content of this article is by quickly executing the code snippet in browser’s console. Follow below steps to launch console in Chrome browser:

  • Open new tab in chrome
  • Right click on page and select “inspect element” from context menu
  • Go to the console panel
  • Start executing Javascript code

Objects are the basic building blocks in Javascript. There is one special object available in Javascript, “this” object. You can see the value of “this” at every line of Javascript execution. The value of “this” is decided based on how the code is being executed.

Before getting started about “this”, we need to understand a little about Javascript runtime environment and how a Javascript code is executed.

Javascript Interpreter and Execution Context

Javascript is a scripting language which means that there is no compilation step in code execution. Interpreter reads the code and executes it line by line. The environment (or scope) in which the line is being executed is know as “Execution Context”. The Javascript runtime maintains a stack of these execution contexts and the execution context present at the top of this stack is currently being executed. The object that “this” refers changes every time execution context is changed.

“this” refers to global object

By default, the execution context for an execution is global which means that if a code is being executed as part of a simple function call then “this” refers to global object. “window” object is the global object in case of browser and in Node.JS environment, a special object “global” will be the value of “this”.
For example:

Immediately Invoked Function Expression (IIFE)

 

Note: If the strict mode is enabled for any function then the value of this will be “undefined” as in strict mode, global object refers to undefined in place of windows object.

For Example:

 

“this” refers to new instance

When a function is invoked with “new” keyword then the function is known as constructor function and returns a new instance. In such cases, the value of “this” refers to newly created instance.
For Example:

In case of person.displayName, “this” refers to new instance person and in case of person2.displayName(), “this” refers to person2 which is a different instance of Person.

“this” refers to invoker object (parent object)

In Javascript, property of an object can be a method or a simple value. When an Object’s method is invoked, “this” refers to the object which contains the method being invoked.

In this example, we are going to use method foo defined in first example.

By above example, it is clear that how value of “this” can be confusing in some cases. The function definition of foo1 is same but when it is being called as a simple function call then “this” refers to global object and when same definition is invoked as an object’s method then this refers to the parent object. So the value of “this” depends on how a method is being invoked as well.

“this” with call, apply methods

A function in javascript is also a special type of object. Every function has call, bind and apply methods. These methods can be used to set custom value of “this” to the execution context of function.
We are going to use the second example defined above to explain the use of call:

The only difference between call and apply method is the way argument is passed. In case of apply, second argument is an array of arguments where in case of call method, arguments are passed individually.

 

“this” with bind method

bind method returns a new method with “this” refers to the first argument passed. We are going to use above example to explain bind method.

“this” with fat arrow function

As part of ES6, there is a new way introduced to define a function.


let displayName = (fn, ln) => {
    console.log(Name: ${fn} ${ln});
};


When a fat arrow is used then it doesn’t create a new value for “this”.  “this” keeps on referring to the same object it is referring, outside the function.

Let’s look into some more examples to test our knowledge about “this”

Since the callback is invoked as a simple function call inside multiple function, “this” refers to global object windows inside execution context of callback method.


Summary

 

 

So now, you can figure out the value of “this” by following these simple rules:

 

 

  • By default, “this” refers to global object which is global in case of NodeJS and windows object in case of browser
  • When a method is called as a property of object, then “this” refers to the parent object
  • When a function is called with “new” operator then “this” refers to the newly created instance.
  • When a function is called using call and apply method then “this” refers to the value passed as first argument of call or apply method.

As you have seen above, the value of “this” can sometimes be confusing but above rules can help you to figure out the reasoning of the value of “this”.
 

Pavan

Pavan Kumar

Blog Author

Pavan is a javascript fanatic who loves converting ideas into applications built over ReactJS, React Native, AngularJs, NodeJs. He is an avid explorer of emerging web standards, frameworks and a keen observer of UX. Website: https://about.me/pavan_k

Leave a Reply

Your email address will not be published. Required fields are marked *

Top comments

Karna

May, 3rd at 12:26pm
Good one bro, I understood how "this" behaves in different context.

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs

20% Discount