What is 'this' in JavaScript: Explanation and Examples
this in JavaScript is a special keyword that refers to the object that is currently running the code. Its value changes depending on how and where a function is called, making it a way to access the current context or owner object.How It Works
Think of this as a pointer that tells you who is currently using or running a piece of code. Imagine you are in a room and you say "I am here"; this is like the "I" that changes depending on who is speaking.
In JavaScript, this changes based on how a function is called. If a function is called as a method of an object, this points to that object. If called alone, this can point to the global object or be undefined in strict mode. This dynamic behavior helps functions work with different objects without rewriting code.
Example
This example shows how this refers to different objects depending on the call:
const person = { name: 'Alice', greet() { console.log(`Hello, my name is ${this.name}`); } }; person.greet(); // 'this' refers to 'person' object const greetFunction = person.greet; greetFunction(); // 'this' is undefined or global object in strict mode
When to Use
Use this when you want a function to work with the object that owns it, without hardcoding the object name. This is useful in methods inside objects or classes, event handlers, and constructors.
For example, in a user interface, event handlers use this to refer to the element that triggered the event. In classes, this helps access properties of the current instance.
Key Points
thisrefers to the current execution context object.- Its value depends on how a function is called.
- In methods,
thispoints to the owning object. - In global functions,
thiscan be the global object orundefinedin strict mode. - Arrow functions do not have their own
this; they usethisfrom the surrounding code.
Key Takeaways
this points to the object running the current code.this in object methods to access the object itself.this from their surrounding scope.this helps write flexible and reusable code.