JavaScript 'this' Context Lost in Function Call

The JavaScript "this" Trap 🪤🔥 The Puzzle: What is the output? 🤔 const obj = { name: "JS", getName() { console.log(this.name); } }; const fn = obj.getName; fn(); Output: undefined Why? 🧠 In JavaScript, this depends on HOW a function is called, not where it is written. Lost Context: const fn = obj.getName only copies the function reference. Standalone Call: When you call fn(), there is no object (no dot) before the function. Global Context: It now runs in the Global Context (window object). Since window.name is not "JS", it returns undefined. How to Fix? 🛠️ ✅ Use .bind(): const fn = obj.getName.bind(obj); ✅ Use .call(): fn.call(obj); ✅ Use Arrow Functions: They inherit this from the surrounding scope. Interview Tip: 💡 Always check the "Call Site." No dot before the function call (like fn()) usually means this is lost! #JavaScript #CodingTips #365DaysOfCode #InterviewPrep #WebDev #FullStack #mern #react #node

To view or add a comment, sign in

Explore content categories