How does this keyword work in JavaScript ?
Last Updated :
29 Jan, 2024
In JavaScript, the this
keyword refers to the object that is executing the current function.
The this
keyword refers to different objects depending on how it is used:
- Global Context:
- When you’re not inside any function or object,
this
refers to the big global environment.
- Example in a browser: Imagine the global environment as the entire window. So,
this
would be like pointing to the window in a browser.
- Function Context:
- Inside a function, what
this
is pointing to depends on how that function is being used.
- Regular Function: If it’s a regular function,
this
can also be pointing to the global environment (like the window), or if you’re in strict mode, it might be undefined.
- Method of an Object: If the function is part of an object (a method), then
this
is pointing to that object.
- Event Handlers:
- In events like clicking a button on a webpage,
this
often points to the specific button you clicked.
- Constructor Functions:
- When you’re creating objects using a constructor function (with
new
), this
refers to the particular object that is being created at that moment.
Share your thoughts in the comments
Please Login to comment...