Day 29 this Keyword Deep Dive
this JavaScript ka sabse confusing concept hai. this ki value depend karti hai ke function kaise call hua — not where it was defined. Call, apply, bind se this explicitly set kar sakte hain.
this ka Context
this context ke hisaab se change hota hai — global, object method, constructor, arrow function.
// 1. Global context
console.log(this); // window (browser) / global (Node)
// 2. Object method — this = object
let user = {
name: "Zohaib",
greet() {
console.log("Hello, " + this.name); // this = user
}
};
user.greet(); // Hello, Zohaib
// 3. Arrow function — this = enclosing scope
let counter = {
count: 0,
start() {
// Regular function — this lost!
// setInterval(function() { this.count++; }, 1000); // ❌
// Arrow function — this inherited from start()
setInterval(() => {
this.count++; // ✅ this = counter
console.log(this.count);
}, 1000);
}
};
call, apply, bind
Explicitly this set karne ke teen tarike.
function introduce(city, hobby) {
return `I'm ${this.name} from ${city}. I love ${hobby}.`;
}
let person = { name: "Zohaib" };
// call — args separately
console.log(introduce.call(person, "Lahore", "coding"));
// apply — args as array
console.log(introduce.apply(person, ["Lahore", "coding"]));
// bind — returns new function (doesn't call immediately)
let boundFn = introduce.bind(person, "Lahore");
console.log(boundFn("gaming")); // call later
// Practical: method borrowing
let dog = { name: "Rex", age: 3 };
let cat = { name: "Kitty", age: 2 };
function info() {
return `${this.name} is ${this.age} years old`;
}
console.log(info.call(dog)); // Rex is 3 years old
console.log(info.call(cat)); // Kitty is 2 years old
🎯 Practice Challenge
greet function banao. call se ek user ke liye, apply se dusre ke liye, bind se third ke liye call karo.