WDD 330: Web Frontend Development II

W01 Learning Activity: Object Methods, "this"

Overview

In this activity, you will learn about the this keyword in JavaScript and how it is used to access properties and methods of an object.

The this method is a special keyword in JavaScript that refers to the current object instance. It is used to access properties and methods of the object within its own context.

In this activity, you will learn about the this keyword in JavaScript and how it is used to access properties and methods of an object.

Prepare

In JavaScript, the this keyword is useful when working with objects and DOM elements because it provides a dynamic reference to the current context — meaning the object or element that is currently executing the code. It has different meanings depending on how it is used.

It allows code reuse in methods and event handlers thus supporting clean, modular code that is easier to maintain.

When you lose the context of this, it no longer refers to the object or element you expect, thus returning undefined or the the global object like the window in browsers.

For example, if you use an arrow function in a DOM event listener, this will not point to the element.

document.querySelector("button").addEventListener("click", () => {
  console.log(this); // ❌ this is not referencing the button element as maybe expected.
  // Arrow functions do not have their own this.
});

To preserve control of this, there are several techniques that are useful, especially when dealing with callbacks or event handlers.

Activity Instructions

Complete the following steps to understand how and why the this keyword behaves in different contexts such as object method, global scope, event handler. The objective is to understand why this is important for accessing the current object instance.

To check your understanding of the activity questions, paste the code snippets into a browser console to run them. Examples of this activity are also provided at the end of the activity for review.

  1. Given the following code snippet, what will this.name refer to?
    const person = {
      name: "Maria",
      greet: function () {
        console.log(`Hello, my name is ${this.name}`);
      }
    };
       
    person.greet();

    What do you expect the output to be?

  2. What happens when the person's method is extracted?
    const greetFunction = person.greet; // Extracting the method
    greetFunction(); // Calling the method

    What is this bound to now?

  3. The previous example can be fixed by using the bind() method to set the value of this explicitly.
    const greetFunction = person.greet.bind(person); // Binding 'this' to person:
    greetFunction();

    What is the output now?

  4. What happens when you use an arrow function in the greet method?
    const person = {
      name: "Maria",
      greet: () => {
        console.log(`Hello, my name is ${this.name}`); // Arrow function does not bind 'this' to the object
      }
    };
    
    person.greet();

    What is the output now?

  5. In the following code snippet, what does this refer to in the event handler?
    const button = document.querySelector("button");
    button.addEventListener("click", function () {
      console.log(this); // 'this' refers to the button element
    });

Example: JavaScript "this" object method

Optional Resources