CodePark/ problems / call and apply
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › this, call/apply/bind and prototypes

call and apply

mediumabout 20 minutes in an interview

Implement two standalone functions that run fn with a chosen this:

  • myCall(fn, thisArg, ...args) passes the arguments one by one.
  • myApply(fn, thisArg, args) takes the arguments as one array or array-like (an object with length and numbered keys). A missing or null args means no arguments.

Both return whatever fn returns. Rules:

  • Don't use Function.prototype.call, apply or bind, and don't use Reflect.apply. Don't modify Function.prototype.
  • If thisArg is null or undefined, run fn with globalThis as this. A primitive thisArg such as 2.25 is wrapped in its object form, so number methods still work on it.
  • thisArg must look exactly the same afterwards: no leftover properties, even if fn throws. It may already have a property with any name, such as fn.
  • If fn is not a function, throw a TypeError.
Input: myCall(function (g) { return g + ' ' + this.name; }, { name: 'Ada' }, 'Hi') Output: 'Hi Ada'
Input: myApply(Math.max, null, [3, 9, 4]) Output: 9