Have you ever found yourself scratching your head while trying to figure out what this
means in JavaScript? If so, you are not alone! Understanding this is similar to learning a new skill: it takes some practice, but once you understand it, everything makes sense.
In this blog, we'll learn what this
is, how it works in various scenarios, and even include some examples to help it stick.
Letβs dive in! π€
π What is this
?
In JavaScript, the this
is a keyword that represents the object to which a function belongs. It allows you to develop reusable and dynamic functions by deciding their value at runtime.
The value of this
is totally dependent on how a function is called. This ability gives it flexibility and confusion at times.
π Key Points about this:
-
this
is not a variable; itβs a keyword. - You cannot assign a new value to
this
. - Its value is determined at runtime.
π Real-Life Analogy for this
Think of this
as a tour guide in a museum.
- When the guide is in the art museum, they represent the art museum.
- When they switch to a history museum, they represent the history museum.
Similarly, the value of this
depends on the "context" (the function call) and changes accordingly.
π‘ Understanding this
in Different Scenarios
1οΈβ£ In the Global Context (Default Binding)
When used outside of a function, this
refers to the global object.
The value of this
in the global context depends on the runtime environment β whether you're in a browser or Node.js.
π Without strict mode
- In the browser,
this
refers to thewindow
object. - In Node.js,
this
refers to the{}
empty object because Node.js wraps your code in a module. Each module has its own scope, andthis
refers to the module's exports.
π Example
console.log(this);
// Output: In browsers, this = window object
// Output: In node.js, this = {}
π With strict mode
- In the browser, the behavior is still the same because
this
is fundamentally linked to the global object (window
). Even strict mode doesn't change this. - In Node.js,
this
still refers to the module's exports, which remains an empty object ({}
).
π Example
'use strict';
console.log(this);
// Output: In browsers, this = window object
// Output: In node.js, this = {}
2οΈβ£ Inside a Regular Function
In a regular function, the value of this
is selected by how the function is called.
π Without strict mode
- In the browser,
this
refers to thewindow
object. - In Node.js,
this
refers to theglobal
global object.
π Example
function showThis() {
console.log(this);
}
showThis();
// Output: In browsers, this = window object
// Output: In node.js, this = global object
π With strict mode
In the browser and Node.js, this
is undefined
.
π Example
'use strict';
function showThis() {
console.log(this);
}
showThis();
// Output: undefined
3οΈβ£ Inside an Object Method (Implicit Binding)
When a function is called as a method of an object, this
refers to the object itself.
π Example
const book = {
title: 'JavaScript: The Dynamic Language',
showTitle: function () {
console.log(this.title);
},
};
book.showTitle(); // Output: JavaScript: The Dynamic Language
Here, this
points to the book object.
4οΈβ£ With Arrow Functions
Arrow functions do not have their own this
. Instead, they inherit this from the surrounding lexical scope (the function or block where they are defined).
π Example
const techBook = {
title: 'JavaScript: A Dynamic Language',
showTitle: function (){
const arrowFunction = () => {
console.log(this.title);
}
arrowFunction();
}
}
techBook.showTitle(); // Output: JavaScript: A Dynamic Language
Why? The arrow function does not generate a new this
; instead, it uses this
of showTitle
.
5οΈβ£ In Constructor Functions (New Binding)
When you use a constructor function with the new
keyword, this refers to the newly created object.
π Example
function Book(title, author){
this.title = title;
this.author = author;
}
const myBook = new Book('Javascript', 'TheDevRicha');
console.log(myBook.title, myBook.author); // Output: Javascript TheDevRicha
6οΈβ£ In Classes
In ES6 classes, this
works similarly to constructor functions.
π Example
class BookInfo{
constructor(title, author){
this.title = title;
this.author = author;
}
showDetails(){
console.log(`${this.title} by ${this.author}`);
}
}
const bookInfo = new BookInfo('Javascript: Beginner Guide', 'TheDevRicha');
bookInfo.showDetails(); // Output: Javascript: Beginner Guide by TheDevRicha
7οΈβ£ Using call()
, apply()
, and bind()
(Explicit Binding)
These methods are in-buit functions in JavaScript. You can explicitly set the value of this
using these methods.
-
call()
: It invokes the function immediately and allows you to pass arguments one by one. -
apply()
: Same ascall()
, but takes arguments as an array. -
bind()
: It doesnβt invoke the function immediately. Instead, it returns a new function with thethis
context set to the specified object. You can invoke it later.
π Example
const member1 = {
firstName: 'Iron',
lastName: 'Man'
}
const member2 = {
firstName: "Jake",
lastName: "Sparrow",
}
function getMembershipDetail(plan, startYear){
console.log(`${this.firstName} ${this.lastName} has a ${plan} plan starting in ${startYear}.`);
}
getMembershipDetail.call(member1, 'Gold', 2024); // Output: Iron Man has a Gold plan starting in 2024.
getMembershipDetail.call(member2, 'Silver', 2025) // Output: Jake Sparrow has a Silver plan starting in 2025.
getMembershipDetail.apply(member1, ['Platinum', 2023]); // Output: Iron Man has a Platinum plan starting in 2023.
getMembershipDetail.apply(member2, ['Bronze', 2022]); // Output: Jake Sparrow has a Bronze plan starting in 2022.
const memberShip1 = getMembershipDetail.bind(member1, 'Diamond', 2027);
const memberShip2 = getMembershipDetail.bind(member2, 'Basic', 2028);
memberShip1(); // Output: Iron Man has a Diamond plan starting in 2027.
memberShip2(); // Output: Jake Sparrow has a Basic plan starting in 2028.
8οΈβ£ In Event Listeners
In regular functions used as event listeners, this
refers to the element that received the event.
π Example
const button = document.querySelector('button');
button.addEventListener('click', function () {
console.log(this); // `this` refers to the button element
});
πͺ Order of Precedence for this
- New binding (Constructor Functions) has the highest priority.
-
Explicit binding (Using
call
,apply
, orbind
) overrides implicit/default binding. - Implicit binding (Object Method) applies when the function is called as a method of an object.
- Default binding (Global Context) is the fallback when no other rule applies.
Conclusion
Mastering this
in JavaScript is essential for creating clean, context-aware code. While it may appear complex at first, understanding how this
behaves in various situations will clarify how it works.
Whether you're working with objects, constructors, or arrow functions, this
is an effective tool for connecting data and behavior in your code. With practice and a clear understanding, you'll realize that this
isn't as mysterious as it first seems.
Share Your Thoughts
Where have you utilized
this
in your projects? What issues or benefits did you encounter? Please let me know in the comments section.
Happy Coding!β¨
Top comments (6)
Well written mate...
Thanks for appreciating!
This is cool. And so is
this
.Thanks for appreciating!
I'm glad you like it.
Thank you for
this
effort.Thanks for appreciating!
I'm glad you like it.