← Daily Logs
GreatFrontEnd

Implement Function.prototype.call

EasyJul 2, 2026javascriptthispolyfillapply

The mirror image of `myApply`: `call` takes its arguments individually where `apply` takes one array. Converting between them just means packing or unpacking that array — the one way to get it backwards is spreading where you should be passing the array whole.

The problem

Implement `Function.prototype.myCall(thisArg, ...argArray)` so that `fn.myCall(obj, a, b)` invokes `fn` with `this` bound to `obj` and called with `a, b` as individual arguments — without using the native `call`.

The rest parameter already collects the individually-passed arguments into `argArray` as a real array; the remaining job is handing that array to something that knows how to invoke a function with `this` bound and an array of arguments — which is exactly what `apply` does.

The approach

`this.apply(thisArg, argArray)` does the whole job: `apply`'s second parameter is expected to be *the array itself*, not individual arguments, so `argArray` gets passed straight through with no spread.

The bug to avoid is `this.apply(thisArg, ...argArray)` — spreading `argArray` here scatters its elements into `apply`'s own parameter list, so `apply` receives `argArray[0]` as its second argument instead of the array. Since `apply` requires that second argument to be an array (or array-like, or `null`/`undefined`), passing a bare value like `2` throws a `TypeError` the moment any argument is provided.

The solution

js
/**
 * @param {any} thisArg
 * @param {...*} argArray
 * @return {any}
 */
Function.prototype.myCall = function (thisArg, ...argArray) {
  return this.apply(thisArg, argArray);
};

Time O(n)Space O(n)

All entries