📞 Function.prototype.apply() Polyfill
Category: js / polyfills
Difficulty: medium
The apply method in JavaScript is similar to call, except that it takes arguments as an array. 1️⃣ Understanding Function.prototype.apply Native behavior: [code example] 📌 Difference from call : call(context, arg1, arg2, arg3, ...) → Arguments are passed individually. apply(context, [arg1, arg2, arg3, ...]) → Arguments are passed as an array. 2️⃣ Polyfill for apply We need to: Attach the function to the thisArg (context). Pass the arguments as an array. Remove the temporary function reference. [code example] 3️⃣ Testing the Polyfill [code example] 4️⃣ Dry Run Step-by-Step Let's break it down for: [code example] 📌 Step 1: Call myApply [code example] this inside myApply refers to greet. context = person ({ name: "Bob" }). args = [30, "Los Angeles"]. 📌 Step 2: Function Definition Breakdown Inside myApply: [code example] ✅ this is greet (a function), so no error. 📌 Step 3: Set context [code example] context = person. 📌 Step 4: Attach Function Temporarily [code example] A unique property is added to person: [code example] 📌 Step 5: Invoke Function [code example] Equivalent to: [code example] Since this is now person, it prints: [code example] 📌 Step 6: Cleanup [code example] Removes the temporary function from person, restoring it to: [code example] 📌 Final Execution Summary Action greet.myApply(person, [30, "Los Angeles"])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 apply method! <!-- quiz-start --> Q1: What is the main difference between call() and apply()? [ ] call() is faster [ ] apply() can change this, call() cannot [x] call() takes arguments individually, apply() takes them as an array [ ] apply() returns a new function, call() invokes immediately Q2: Why is a Symbol used as the function key in the polyfill? [ ] For better performance [x] To avoid property name collisions on the context object [ ] To make the function enumerable [ ] It's require...