"Understanding JavaScript's this keyword in different scenarios"

“Why does this behave so weird in JavaScript? 🤯 Let’s finally make sense of it!” If you’ve ever shouted at your screen because this suddenly became undefined — you’re not alone 😅 Let’s break down how this works across different scenarios with simple examples 👇 🧩 1️⃣ Arrow Function Defined Directly in Object const person = { name: "Suverk", greet: () => console.log(`Hi ${this.name}`) }; person.greet(); // ❌ undefined 🧠 Why? Arrow functions don’t have their own this. They lexically inherit this from their surrounding scope — which here is the global (not person). ✅ Fix: Use a regular function: greet() { console.log(`Hi ${this.name}`); } 🧩 2️⃣ Arrow Function Inside a Regular Method const person = { name: "Suverk", greet: function() { const arrow = () => console.log(this.name); arrow(); } }; person.greet(); // ✅ "Suverk" 🧠 Why? The arrow function inherits this from where it was created — inside greet, and this inside greet = person. ✅ Works perfectly because of lexical scoping. 🧩 3️⃣ Regular Function Inside Another Regular Function const person = { name: "Suverk", greet: function() { function inner() { console.log(this.name); } inner(); } }; person.greet(); // ❌ undefined 🧠 Why? When you call inner() as a plain function, it’s not attached to any object. So this defaults to global (or undefined in strict mode). ✅ Fixes: // Option 1 const self = this; function inner() { console.log(self.name); } // Option 2 function inner() { console.log(this.name); } inner.bind(this)(); // Option 3 const inner = () => console.log(this.name); 🧩 4️⃣ Detached Method Reference const person = { name: "Suverk", greet() { console.log(this.name); } }; const use = person.greet; use(); // ❌ undefined 🧠 Why? this depends on how a function is called. You’ve just taken the function reference — the link to person is gone. ✅ Fix: const use = person.greet.bind(person); use(); // ✅ "Suverk" In JavaScript, this depends on how a function is called — except for arrow functions, which depend on where they’re defined. 💬 Have you ever been tricked by this before? Drop your comment below 👇 — let’s make others learn faster than we did 😅 #JavaScript #Frontend #WebDevelopment #Angular

To view or add a comment, sign in

Explore content categories