This Keyword

What is this
in JavaScript? (Definition & Importance)
The this
keyword in JavaScript is a special identifier that refers to the object that is currently executing the function or code in which it appears. Its value is determined by how a function is called, not where it is defined. This dynamic nature makes this
both powerful and sometimes confusing. It enables context-aware operations, access to object properties and methods, and is fundamental to object-oriented and event-driven programming in JavaScript234.
Importance of this
:
Provides dynamic context for function execution.
Facilitates object-oriented code by allowing methods to reference their own object.
Enables event handling by referring to DOM elements in event listeners.
Global Context (this
in the Global Scope)
In the global scope (outside any function or object),
this
refers to the global object:In browsers:
window
In Node.js:
global
Example:
jsconsole.log(this); // window (in browser)
Assigning properties to
this
in the global scope attaches them to the global object28.
this
in Strict Mode ('use strict'
)
In strict mode,
this
in global or standalone function context isundefined
, not the global object.Example:
js'use strict'; function show() { console.log(this); // undefined } show();
This prevents accidental modifications to the global object26.
Function Context & this
this
in Regular Functions
When a regular function is called in the global context,
this
refers to the global object (orundefined
in strict mode).When called as a method of an object,
this
refers to the object owning the method27.
this
in Arrow Functions (Lexical this
)
Arrow functions do not have their own
this
. Instead, they inheritthis
from their surrounding (lexical) scope.Useful for preserving context in callbacks and nested functions4.
Example:
jsconst obj = { value: 10, method: function() { setTimeout(() => { console.log(this.value); // 10 }, 100); } }; obj.method();
this
in Object Methods
When a function is called as a method of an object,
this
refers to that object.Example:
jsconst user = { name: "Alice", greet: function() { console.log(this.name); // "Alice" } }; user.greet();
this
in Constructor Functions (new
keyword)
When a function is called with
new
,this
refers to the newly created instance.Example:
jsfunction Person(name) { this.name = name; } const p = new Person("Bob"); console.log(p.name); // "Bob"
Dynamic Binding of this
Explicit Binding (call
, apply
, bind
)
You can explicitly set the value of
this
for any function usingcall
,apply
, orbind
.Example:
jsfunction show() { console.log(this.name); } const user = { name: "Carol" }; show.call(user); // "Carol"
bind
returns a new function with permanently boundthis
5.
Implicit Binding (Object Property Call)
When a function is called as a property of an object,
this
is set to that object.Example:
jsobj.method();
Default Binding
- If none of the above rules apply,
this
defaults to the global object (orundefined
in strict mode)36.
Lost Binding
Assigning a method to a variable or passing it as a callback can cause
this
to lose its intended context (becoming global orundefined
).Example:
jsconst greet = user.greet; greet(); // `this` is global or undefined
Advanced Concepts
this
inside Event Listeners
In regular functions,
this
refers to the DOM element that received the event.In arrow functions,
this
is inherited from the outer scope (often not the element)4.
Arrow Functions vs Regular Functions in Callbacks
Arrow functions inherit
this
from the parent scope.Regular functions assign
this
based on how they are called.
this
inside Classes & Class Methods
In ES6 classes,
this
inside methods refers to the instance of the class.Arrow functions as class properties can help preserve
this
in callbacks.
this
inside setTimeout
& setInterval
Regular functions:
this
defaults to global orundefined
.Arrow functions:
this
is inherited from the enclosing scope4.
this
inside Promises, Async/Await
- Inside promise callbacks or async functions,
this
follows the same rules as regular or arrow functions.
this
in Array Methods (map
, forEach
, filter
, etc.)
Regular functions:
this
is global orundefined
unless explicitly bound.Arrow functions:
this
is inherited from the parent scope.
this
in ES6 Modules vs CommonJS Modules
In ES6 modules, top-level
this
isundefined
.In CommonJS (Node.js), top-level
this
ismodule.exports
.
Practical Applications
Handling this
in React Components
Class Components:
this
refers to the component instance; methods often need to be bound in the constructor or defined as arrow functions.Functional Components: No
this
; use hooks for state and lifecycle.
How this
works in Event Delegation
- In event delegation,
this
refers to the element that triggered the event, allowing generic handlers.
Fixing this
Issues in JavaScript Code
Use arrow functions to preserve the outer
this
.Use
bind
,call
, orapply
to explicitly setthis
.Store reference to
this
in a variable (const self = this
) in older code.
Summary Table: this
Behavior in Different Contexts
Context | Value of this |
Global scope | Global object (window /global ) |
Function (non-strict) | Global object |
Function (strict mode) | undefined |
Object method | The object |
Constructor (new ) | New instance |
Arrow function | Lexically inherited from parent scope |
Event listener (regular function) | Event target (DOM element) |
Event listener (arrow function) | Lexically inherited from parent scope |
call/apply/bind | Explicitly set by the method |
Tasks
Using "this" in object literal
Here the function m
ak
eUser
returns an object.
What is the result of accessing its ref
? Why?
function makeUser() {
return {
name: "John",
ref: this
};
}
let user = makeUser();
alert( user.ref.name );
Create a calculator
Create an object calculator
with three methods:
read()
prompts for two values and saves them as object properties with namesa
andb
respectively.sum()
returns the sum of saved values.mul()
multiplies saved values and returns the result.
let calculator = {
// ... your code ...
};
calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );
Chaining
There’s a ladder
object that allows you to go up and down:
let ladder = {
step: 0,
up() {
this.step++;
},
down() {
this.step--;
},
showStep: function() {
alert( this.step );
}
};
Now, if we need to make several calls in sequence, we can do it like this:
ladder.up();
ladder.up();
ladder.down();
ladder.showStep(); // 1
ladder.down();
ladder.showStep(); // 0
Modify the code of up
, down
, and showStep
to make the calls chainable, like this:
ladder.up().up().down().showStep().down().showStep();
Subscribe to my newsletter
Read articles from priyanka kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
