Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 19 - The this Keyword in Arrow Functions vs. Regular Functions

I introduced functions to you in lesson 11, and then introduced arrow function in lesson 13. In this lesson, I would like to take you to the discovery of the "this" keyword. It's used to represent JavaScript objects. But, the "this" keywork does not behave the same way depending on the type of function.

Let's see how it works.

const person = {
    name: "Alice",
    regularFunction: function() {
        console.log("Regular Function:", this.name);
    },
    arrowFunction: () => {
        console.log("Arrow Function:", this.name);
    }
};

person.regularFunction(); // Output: Regular Function: Alice
person.arrowFunction();   // Output: Arrow Function: undefined

Explanation:

  • The this keyword in regular functions refers to the object that calls the function (in this case, person).
  • The this keyword in arrow functions does not refer to the calling object. Instead, it inherits this from its surrounding scope.
  • This is why this.name is undefined inside arrowFunction, while regularFunction correctly accesses person.name.

Try your hand:

Steps:

  1. Create a File:

    • Create a new file named lesson19-this-keyword.html.
  2. Write the Code:

    • Copy and paste the following code into your file:
    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Lesson 19 - The this Keyword</title>
    </head>
    <body>
       <script>
           const user = {
               name: "John",
               showName: function() {
                   console.log("Regular Function:", this.name);
               },
               showNameArrow: () => {
                   console.log("Arrow Function:", this.name);
               }
           };
    
           user.showName();       // Output: Regular Function: John
           user.showNameArrow();  // Output: Arrow Function: undefined
       </script>
    </body>
    </html>
  3. Save the File:

    • Save the file in your folder.
  4. Preview the File:

    • Open the file in your browser and access the developer console.
    • Observe the output:
      Regular Function: John
      Arrow Function: undefined
  5. Experiment:

    • Try using setTimeout inside an object method:

      const obj = {
       name: "Bob",
       delayedGreeting: function() {
           setTimeout(function() {
               console.log("Hello, " + this.name);
           }, 1000);
       }
      };
      
      obj.delayedGreeting(); // Output: Hello, undefined (this is not bound)
    • Fix the issue using an arrow function:

      const objFixed = {
       name: "Bob",
       delayedGreeting: function() {
           setTimeout(() => {
               console.log("Hello, " + this.name);
           }, 1000);
       }
      };
      
      objFixed.delayedGreeting(); // Output: Hello, Bob

Key Takeaways:

  • Regular functions have their own this, which refers to the calling object.
  • Arrow functions do not have their own this, instead, they inherit it from the surrounding scope.
  • Be careful when using arrow functions inside objects, as they may not behave as expected when using this.