Function.prototype.apply
JS Functions
Medium
15 min
this
functions
polyfills
symbols
Implement Function.prototype.myApply(thisArg, argsArray), a polyfill for Function.prototype.apply. It invokes the function with this set to thisArg and the elements of argsArray as the arguments, and returns the result.
The starter attaches the function to Function.prototype and default-exports it.
function total(a, b, c) {
return this.base + a + b + c;
}
total.myApply({ base: 10 }, [1, 2, 3]); // 16
Math.max.myApply(null, [4, 9, 2]); // 9
total.myApply({ base: 0 }, { length: 3, 0: 1, 1: 1, 2: 1 }); // 3 (array-likes work)
Requirements
- Do not use
call,apply,bindorReflect.apply. argsArraymay benullorundefined, which means "no arguments".- Otherwise
argsArraymust be an object. Read itslengthand indices0..length-1(holes read asundefined). Throw aTypeErrorfor primitives such as numbers or strings, as the native method does. - Throw a
TypeErrorifmyApplyis invoked on something that is not a function. thisArgfollows the same rules as themyCallexercise: primitives are boxed, andnull/undefinedbecomesglobalThis. Any temporary property must not collide with existing keys and must be cleaned up even if the function throws.
Follow-up
- Why was
fn.apply(null, arr)so common before ES2015, and what replaced it? - Is there a limit to how many arguments you can pass with
applyor spread?
Spotted a mistake or a rights concern? Report an issue