Explain the concept of "this" keyword in JavaScript.
369
26-Jun-2024
Updated on 26-Jun-2024
Ashutosh Kumar Verma
26-Jun-2024JavaScript “this” Keyword
In JavaScript,
thiskeyword refers to the currently active object. Its value depends on how the function is called (runtime binding) and enables functions to access and manipulate data within an object.Global Context
In a global context,
thisrefers to a global object (window in browser, global in Node.js).Function Context
In a function,
thisrefers to the object that calls the function (the receiver).Object Method
When a function is called as a method of an object,
thisspecifies the object on which the method is called.Constructor Function
When a function is used as a constructor with the
newkeyword,thisdisplays an instance of the object being created.Event Handlers
In event handlers
thisrefers to the element that received the event (if you are using traditional event handlers) or the target element (if you are using event delegation).In this example,
thisrefers to the<button>element that is clicked.