How 'this' behaves in JavaScript: A Deep Dive

Why does this act weird in JavaScript? 💭 Ever wondered why this in JavaScript sometimes feels possessed? Let’s break the magic (and madness) behind it 👇 this depends on how a function is called, not where it’s written. JavaScript doesn’t decide the value of this when you write the function, but only when you call it — and how you call it changes what this means. **Some definitions that are needed to understand the post ** what is Binding is the way JavaScript decides what this refers to when a function is called. 👉 In short: Binding = the connection between this and its value (object/global/undefined). 🧩 Types of Binding Dynamic binding → this depends on how the function is called. Lexical binding → this is inherited from where the function was written (arrow functions). Manual binding → you set this yourself using .call(), .apply(), or .bind(). 💡 How this Behaves in Every Case (JavaScript) 1️⃣ Global Scope console.log(this===window) In browsers: this = window In strict mode: still window (only inside functions it becomes undefined) this refers to the global object. 2️⃣ Inside a Normal Function Non-strict mode: this = window Strict mode: this = undefined Because the function isn’t called by any object — so this defaults to global (or undefined in strict mode). 3️⃣ Inside an Arrow Function Non-strict mode: this = window Strict mode: this = undefined Arrow functions don’t have their own this. Instead, they lexically inherit this from the surrounding scope (where they were created). 🧠 In simple words: Arrow functions use the this value of their outer function — they never create a new one.  4️⃣ Inside an Object Method this refers to the object that owns the method → user. That’s called dynamic binding (decided by how it’s called). 🔶 Normal function is automatic dynamicly binding by js which this inside it refers to the object . 🔶Arrow function dynamic is lexical binding which means only lexical scops like global ,function or block scoop that inherit it's this value from it so this will not refer to the object 🔶Nested functions When a function is declared inside another function, the inner normal function doesn’t automatically inherit this from the outer one. 🧠 In simple words: Each normal function has its own this — it doesn’t care about its parent. 📉 Result: In non-strict mode → this = window In strict mode → this = undefined because the inner function isn’t called by any object that means no dynamic binding for the inner One obj =>one normal fun So what are the solutions that we have ?? 🅰️ Arrow function as an inner function because of it's lexical binding to inherit this value from the outer() 🅱️ Manual binding to force the inner function in the normal form (Not arrow) to refer to the outer #JavaScript #CodingTips #Frontend #WebDevelopment #LearningJS #WomenInTech #SamiaLearnsJS

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories