Skip to content
Onsite

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) calls fn with this set to thisArg and the remaining arguments, and returns its result.
  • myApply(fn, thisArg, argsArray) does the same with the arguments given as an array (or nothing, when argsArray is null or undefined).

Rules, as in sloppy-mode JavaScript:

  • If thisArg is null or undefined, this is globalThis.
  • If thisArg is a primitive (number, string, boolean), this is its object wrapper, for example Object(5).
  • Do not use call, apply or bind. Do not leave any property behind on thisArg after 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

Run checks the 3 visible tests, Submit all 9.