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.
Here are the common scenarios where this is used:
this refers to the owner
object.this refers to the Global object (Window in
browsers).this refers to the Global
object.this is
undefined.this refers to the element
that received the event.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;
}
};
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>
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.
this.
They inherit this from the surrounding code (lexical scope). This is one of
their most powerful features!
this is not a variable—it is a keyword whose value is determined by the "call site"this is contextual and dynamicthis in functions is undefined to prevent accidental globalsbind() to "lock in" the this value for future usethis is the Target Elementthis rules by using lexical scoping