Open In App

How does this keyword work in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. 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.
  2. 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.
  3. Event Handlers:
    • In events like clicking a button on a webpage, this often points to the specific button you clicked.
  4. 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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads