📞 Function.prototype.call() Polyfill
Category: js / polyfills
Difficulty: medium
The call method in JavaScript allows us to invoke a function with a specified this context and arguments. Let's implement a polyfill for it. 1️⃣ Understanding Function.prototype.call Native behavior: [code example] Here, call(person) makes this inside greet refer to person. 2️⃣ Polyfill for call We need to: Attach the function to the thisArg (context). Invoke the function with arguments. Remove the temporary function reference. [code example] 3️⃣ Testing the Polyfill [code example] 4️⃣ Key Features of Our Polyfill ✅ Handles any function ✅ Supports multiple arguments ✅ Avoids polluting original object using Symbol ✅ Works in any execution environment (globalThis) Dry Run of myCall Polyfill Let’s take an example and go step by step to understand how our polyfill works. 📌 Example [code example] 📌 Step-by-Step Execution Step 1: Call myCall [code example] this inside myCall refers to greet (the function being invoked). context is person ({ name: "Bob" }). args = [30]. Step 2: Function Definition Breakdown Inside myCall: [code example] 📌 Step 3: Execution Flow 1️⃣ Validate this [code example] this is greet, which is a function ✅. No error is thrown. 2️⃣ Set context [code example] context = person, since it was provided ({ name: "Bob" }). 3️⃣ Attach Function Temporarily [code example] Symbol() creates a unique property key (e.g., Symbol(fnKey)) to avoid overwriting existing properties . person now has a new temporary property: [code example] So person looks like this: [code example] 4️⃣ Invoke Function [code example] Equivalent to: [code example] Since this inside greet is now person, it prints: [code example] 5️⃣ Cleanup [code example] Removes the temporary function from person to keep the object clean. person is now back to: [code example] 📌 Final Execution Summary Action greet.myCall(person, 30)is called 2️⃣ Symbol(fnKey)is created and assigned to person[Symbol(fnKey)] = greet 4️⃣ Temporary function property is deleted | ✅ Works just like the native call method! <!-...