JavaScript this keyword explained

📊 Day 8 – Poll Answer & Explanation const obj = { a: "foo", b: function () { console.log(this.a); }, }; const c = obj.b; obj.b(); c(); 🧠 Concept: this binding in JavaScript In JavaScript, this is determined by how a function is called, not where it is defined. 🔍 Step-by-step explanation ✅ Method call obj.b(); b is called using the object So this refers to obj this === obj this.a // "foo" ✔️ Output: foo ⚠️ Function reference const c = obj.b; Only the function reference is copied The object context is lost ❌ Normal function call c(); Called as a regular function this points to: window (browser, non-strict mode) undefined (strict mode) this.a // undefined ❌ Output: undefined 🖨️ Final Output foo undefined 🎯 Key Takeaway this depends on the call-site, not the function definition. When a method is assigned to a variable and called, it loses its object context. 💡 Tip: Use bind, call, or apply if you want to preserve this. const c = obj.b.bind(obj); c(); // foo #JavaScript #ThisKeyword #JSConcepts #TrickyQuestions #Frontend #PollAnswer

To view or add a comment, sign in

Explore content categories