HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

The "this" Keyword

The JavaScript this keyword refers to the object it belongs to. It has different values depending on where it is used. Understanding this is essential for working with objects, classes, and complex event handlers.


Contextual Values

Here are the common scenarios where this is used:

  • In a method, this refers to the owner object.
  • Alone, this refers to the Global object (Window in browsers).
  • In a function, this refers to the Global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.

Example: Object Method

In this example, this refers to the person object because the fullName method is owned by the person object.

const person = {
  firstName: "Jane",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

this in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event.

<button onclick="this.style.display='none'">
  Click to Remove Me!
</button>

Explicit Function Binding

Methods like call() and apply() allow you to assign this to a specific object when calling a function. You can "borrow" methods from one object and use them for another.

Arrow Functions: Arrow functions do not have their own this. They inherit this from the surrounding code (lexical scope). This is one of their most powerful features!

Key Points to Remember

  • this is not a variable—it is a keyword whose value is determined by the "call site"
  • The value of this is contextual and dynamic
  • In strict mode, this in functions is undefined to prevent accidental globals
  • Use bind() to "lock in" the this value for future use
  • In DOM listeners, this is the Target Element
  • Arrow functions skip the usual this rules by using lexical scoping