Understanding the this Keyword in JavaScript
JavaScript can feel simple—until you encounter this.
Many beginners get confused because this doesn’t behave the same way everywhere. But once you understand one core idea, everything becomes much clearer:
👉 this refers to the object that is calling the function.
Let’s break it down step by step.
🚀 What this Represents
At its core:
this= the caller of the function
It does NOT depend on where the function is written. It depends on how the function is called.
🌍 this in Global Context
In the global scope:
console.log(this);
In Browser:
// Output:
window
👉 So in a browser, this refers to the global object (window)
📦 this Inside Objects
When a function is called as a method of an object:
const user = {
name: "Sayantan",
greet: function () {
console.log(this.name);
}
};
user.greet();
Output:
Sayantan
👉 Here, this refers to user, because user is calling greet().
⚙️ this Inside Functions
Now look at a normal function:
function show() {
console.log(this);
}
show();
Output (in browser):
window
👉 Why?
Because the function is called independently, so the default caller becomes the global object.
🔄 How Calling Context Changes this
This is the most important concept.
Let’s use the same function, but call it differently:
const person = {
name: "Sayantan",
sayName: function () {
console.log(this.name);
}
};
const anotherPerson = {
name: "Alex"
};
anotherPerson.sayName = person.sayName;
anotherPerson.sayName();
Output:
Alex
👉 Even though the function was written inside person, 👉 this now refers to anotherPerson
Because anotherPerson is calling it.
🧠 Key Rule to Remember
✅
thisis determined at call-time, not at write-time
⚡ Simple Mental Model
Whenever you see this, ask:
👉 “Who is calling this function?”
That object is what this will be.
📌 Common Mistake
const user = {
name: "Sayantan",
greet: function () {
function inner() {
console.log(this.name);
}
inner();
}
};
user.greet();
Output:
undefined
👉 inner() is called like a normal function 👉 So this becomes the global object (not user)