JavaScript mein object ek collection hota hai key-value pairs ka. Har key ko property kehte hain aur value koi bhi data type ho sakta hai.
"this" keyword current object ko refer karta hai jiske andar function call ho raha hai.
👉 Simple words:
this= jis object ne function call kiya
const person = {
name: "Sandhya",
age: 22,
// method (function inside object)
greet: function () {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // Output: Hello, my name is SandhyaAgar hum directly name likhen:
const user = {
name: "Rahul",
greet: function () {
console.log("Hello " + name); // ❌ ERROR
}
};
// user.greet(); // Uncomment karoge toh error aayegaconst user2 = {
name: "Rahul",
greet: function () {
console.log("Hello " + this.name); // ✅
}
};
user2.greet(); // Output: Hello Rahulconst obj1 = {
name: "Object1",
show: function () {
console.log(this.name);
}
};
const obj2 = {
name: "Object2"
};
obj2.show = obj1.show;
obj1.show(); // Output: Object1
obj2.show(); // Output: Object2👉 Key Point: Same function hai, but jis object se call ho raha hai, this usi ko refer karega.
const arrowObj = {
name: "Sandhya",
greet: () => {
console.log(this.name);
}
};
arrowObj.greet(); // Output: undefined- Arrow function apna
thiscreate nahi karta - Wo parent scope ka
thisuse karta hai - 👉 Isliye object methods ke liye arrow function avoid karo
const correctObj = {
name: "Sandhya",
greet: function () {
console.log(this.name);
}
};
correctObj.greet(); // Output: Sandhyaconsole.log(this); // Browser mein: Window object
// Node.js mein: global object| Scenario | "this" Refers To |
|---|---|
| Object method (normal function) | Object itself |
| Object method (arrow function) | Parent scope's "this" |
| Global scope | window/global object |
| Event handler | HTML element |
| Constructor function | New instance |