Function.prototype.call and apply Polyfill
MediumP2Coding
Implement polyfills for Function.prototype.call and Function.prototype.apply as standalone functions (so nothing global is modified).
myCall(fn, thisArg, ...args)callsfnwiththisset tothisArgand the remaining arguments, and returns its result.myApply(fn, thisArg, argsArray)does the same with the arguments given as an array (or nothing, whenargsArrayisnullorundefined).
Rules, as in sloppy-mode JavaScript:
- If
thisArgisnullorundefined,thisisglobalThis. - If
thisArgis a primitive (number, string, boolean),thisis its object wrapper, for exampleObject(5). - Do not use
call,applyorbind. Do not leave any property behind onthisArgafter the call.
Example 1
- Input
- function hi(g) { return g + ', ' + this.name; } myCall(hi, { name: 'Ada' }, 'Hello') myApply(hi, { name: 'Ada' }, ['Hi'])
- Output
- 'Hello, Ada' 'Hi, Ada'
Constraints
- fn is a function.
- argsArray has at most 10^3 items.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.