Everything about 'This' keyword :

The this keyword of JavaScript seems confusing to the beginners โ but once you understand who is calling the function, everything becomes easy.
Golden Rule:this always refers to the caller of the function.
๐น 1. What does this represent?
this is a special keyword which represent current execution context .
In Simple words :this = "who call the function"
๐น 2. this in Global Context
When you use this in global scope:
console.log(this);
In Browser โ window object
In Node.js โ {} (empty object)
So:
Browser:
this === windowNode: different behavior
๐น 3. this inside Objects
When function is inside the object:
const user = {
name: "Radhika",
greet: function () {
console.log(this.name);
}
};
user.greet();
Output: "Radhika"
Here, this = user object
because user call the greet function.
๐น 4. this inside Functions
In normal function this shows tricky behaviour :
function show() {
console.log(this);
}
show();
Browser โ window
Strict mode โ undefined
"use strict";
function show() {
console.log(this);
}
show(); // undefined
There is no specific caller here โ default behavior
๐น 5. How Calling Context Changes this
Same function, different this:
function sayHello() {
console.log(this.name);
}
const user1 = { name: "Rr", sayHello };
const user2 = { name: "Alex", sayHello };
user1.sayHello(); // Rr
user2.sayHello(); // Alex
Function are same
But caller changes โ as this changes
๐น Visual Understanding
user1 ----calls----> sayHello() โ this = user1
user2 ----calls----> sayHello() โ this = user2
So
thisdepends on who calls the function, not where it is written
๐น 6. Common Mistake
const user = {
name: "Rr",
greet: function () {
function inner() {
console.log(this.name);
}
inner();
}
};
user.greet();
Output: undefined
As we call inner() directly.
So this = global (or undefined in strict mode)
๐น 7. Fix Using Arrow Function
const user = {
name: "Rr",
greet: function () {
const inner = () => {
console.log(this.name);
};
inner();
}
};
user.greet();
Output: "Rr"
Arrow function don't create their own this
They use this of their parent.
๐น 8. Quick Summary
| Situation | this value |
|---|---|
| Global scope | window (browser) |
| Object method | Object itself |
| Normal function | window / undefined |
| Strict mode | undefined |
| Arrow function | Parent's this |
๐น Final Takeaway
this is never decided inside the function.this is always decided at the time of calling function.
Remember this line:
โ
thisis not about where the function is written, it's about who calls it.โ
Hope you got the ides about this.
Thank you for reading this blog. I am open to feedback and suggestions.





