Explain the concept of "this" keyword in JavaScript.
122
26-Jun-2024
Updated on 26-Jun-2024
Ashutosh Kumar Verma
26-Jun-2024JavaScript “this” Keyword
In JavaScript,
this
keyword 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,
this
refers to a global object (window in browser, global in Node.js).Function Context
In a function,
this
refers to the object that calls the function (the receiver).Object Method
When a function is called as a method of an object,
this
specifies the object on which the method is called.Constructor Function
When a function is used as a constructor with the
new
keyword,this
displays an instance of the object being created.Event Handlers
In event handlers
this
refers 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,
this
refers to the<button>
element that is clicked.