How does the “this” keyword work in JavaScript?

Front End TechnologyJavascriptWeb Development

If you came across the languages like Java, C#, PHP, etc. you must hear about the this keyword, In JavaScript, it works a little differently in comparison to other languages. In this article, we will discuss the this keyword and how to use it in different contexts, and what outcome we get in a different context. For a beginner, it might be a little tedious but this article has the simplicity to make a beginner learn about this concept.

In simple words, the “this” keyword refers to any object, and which object it references depends upon how and where we used the this keyword. In different conditions, the this keyword refers to different objects.

Let’s see with some examples of different contexts of the this keyword and see the result.

In Global Context

When used alone it refers to the global object which is [object Window] in the browser.

Example 1

In this example, we are printing the value of this in the global context.

<html> <body> <h2> The value of "this" in global context is : </h2> <div id ="result"></div> <script> document.getElementById("result").innerHTML = this; </script> </body> </html>

When used in a Global context with Strict mode then also it Refers to the same global object.

Example 2

In this example, we are printing the value of this in the global context and using the strict mode.

<html> <body> <h2>Value of "this" in global context in strict mode:</h2> <div id ="result"></div> <script> "use strict" document.getElementById("result").innerHTML = this; </script> </body> </html>

In a globally defined function also the this keyword refers to the Global Object because the function is a method of the Global object.

Example 3

In this example, we defined a function named tp and printed the value of this inside the function.

<html> <body> <h2>Value of "this" in a globally defined function:</h2> <div id ="result"></div> <script> function tp(){ document.getElementById("result").innerHTML = this; } tp(); </script> </body> </html>

But in the strict mode, the this inside the function defined globally will refer to undefined

Example 4

This is the same example as above but we used the strict mode here.

<html>
<body>
   <h2> Value of this is globally defined function in strict mode </h2>
   <div id ="result"></div>
   <script>
      "use strict"
      function tp(){
         document.getElementById("result").innerHTML = this;
      }
      tp();
   </script>
</body>
</html>

Inside the Object Methods

When used in the object the this refers to the most recent enclosing object whether it is the strict mode or non-strict mode.

Example 1

In this example, we created an object which has two properties names firstName and lastName, and a method that returns the fullname by summing up the firstName and lastName. We used this keyword to get the values of the properties.

<html>
<body>
   <h2> Reference of this inside the object method</h2>
   <div id ="result"></div>
   <script>
      let name = {
         firstName: "Saurabh",
         lastName: "Jaiswal",
         fullName : function () {
            return this.firstName + " " + this.lastName;
         }
      }
      document.getElementById("result").innerHTML = name.fullName()
   </script>
</body>
</html>

If we use the arrow function then the this will refer to undefined.

Example 2

This example is the same as above but instead of using the simple function, we used the arrow function to check the behavior of the this keyword.

<html> <body> <h2>Reference of this inside an object method while using arrow function</h2> <div id ="result"></div> <script> let name = { firstName: "Saurabh", lastName: "Jaiswal", fullName : () => { return this.firstName + " " + this.lastName; } } document.getElementById("result").innerHTML = name.fullName() </script> </body> </html>

Inside the Constructors

Inside the constructor, this refers to the object which is being created.

Example

In this example, we are creating a constructor named Person which returns the fullname.

<html> <body> <h2> Value of this inside Function constructor </h2> <div id ="result"></div> <script> function Person () { this.firstName = "Saurabh" this.lastName = "Jaiswal" this.fullName = function(){ return this.firstName + " " + this.lastName; } } let person1 = new Person(); let person2 = new Person(); document.getElementById("result").innerHTML = person1.fullName() + "<br>"; document.getElementById("result").innerHTML += person2.fullName(); </script> </body> </html>

Here we created 2 objects of Person named person1 and person2, every time we create a new object the this keyword refers to that object.

With Event Handlers

When used with event handlers it refers to the element at which the event occurred.1

Example 1

In this example, we created a button having an attribute name onClick and we are printing the value of this by adding the inline JavaScript.

<html> <body> <h2>Value of this inside Event-Listener</h2> <button onclick="document.write(this)">Click Me</button> </body> </html>

Example 2

While using the addEventListener method with the arrow function the this refers to the global object.

<html> <body> <h2> Value of this inside Event-Listener </h2> <button id="btn">Click Me</button> <script> let btn = document.getElementById("btn"); btn.addEventListener("click", () => { document.write(this) }) </script> </body> </html>

Example 3

But if you create the callback function using the function keyword then the value of this will be the element by which the event is fired.

<html> <body> <h2> Value of this inside Event-Listener </h2> <button id="btn">Click Me</button> <script> let btn = document.getElementById("btn"); btn.addEventListener("click", function () { document.write(this) }) </script> </body> </html>
raja
Updated on 11-Aug-2022 11:42:16

Advertisements