Function.prototype.apply Polyfill
FunctionsPolyfillthis binding
Implement Function.prototype.myApply.
Function Signature:
Function.prototype.myApply = function (context, args) { }
Requirements:
- Same context handling as
call: null/undefined → globalThis, primitives → Object() argsis a single array (or array-like) of arguments — spread it into the call- If
argsis omitted or not an array, call the function with no arguments - Use a Symbol key, clean up after invocation, return the result
Examples
Example 1
Input
function sum(a, b, c) { return a + b + c; }
sum.myApply(null, [1, 2, 3])Output
6Explanation
The array [1, 2, 3] is spread as individual arguments.
Example 2
Input
Math.max.myApply(null, [3, 1, 4, 1, 5])Output
5Explanation
Classic use case: spread an array into a variadic function.
Constraints
- Check `Array.isArray(args)` before spreading — say so if you skip array-like support
Hints
Editorial: Function.prototype.apply Polyfill
Implementing Function.prototype.apply from scratch
apply is identical to call except arguments arrive as a single array rather than individually. All the this binding logic is the same.
Implementation
Function.prototype.myApply = function (context, args) { context = context === null || context === undefined ? globalThis : Object(context); const fnKey = Symbol("fn"); context[fnKey] = this; const result = Array.isArray(args) ? context[fnKey](...args) : context[fnKey](); delete context[fnKey]; return result; };
Key difference from call
The only new piece: handle the args parameter safely.
- If
argsis an array → spread it:context[fnKey](...args) - If
argsis omitted or not an array → call with no arguments:context[fnKey]()
The native apply also accepts array-like objects (anything with .length). For an interview, Array.isArray is enough — just say "the real apply also handles array-likes via Array.from, I've kept this simple for clarity."
Classic use case
// Apply a variadic function to an array of values const numbers = [3, 1, 4, 1, 5, 9]; Math.max.myApply(null, numbers); // 9 // Before spread syntax, this was the standard way to do it // Now you'd write Math.max(...numbers)
Edge cases to mention
- Same context handling as
call:null/undefined→globalThis, primitives →Object() - Same Symbol-key cleanup
argsbeingnullis valid — treat same as omitted (no arguments)
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it