Skip to the page

Polyfills interviewers ask · core

bind, call and apply polyfills

myCall temporarily attaches the function to the context object under a unique Symbol key and calls it as a method, and myBind returns a normal function that calls the original with the bound this and arguments — except when it is called with new, where it must ignore the bound this.

The notes

What you must know

  • myCall(ctx, ...args): ctx = ctx ?? globalThis, Object(ctx) for primitives; const key = Symbol(); ctx[key] = this; const result = ctxkey; delete ctx[key]; return result.
  • myApply is the same with an array of arguments (treat null or undefined as no arguments).
  • myBind(ctx, ...bound) returns function boundFn(...args) { return new.target ? Reflect.construct(fn, [...bound, ...args], new.target) : fn.apply(ctx, [...bound, ...args]); }. The older 'this instanceof boundFn' check also works.
  • The wrapper must be a normal function. An arrow wrapper can't be called with new.
  • Only link prototypes when fn.prototype exists. Arrow functions, methods and built-ins like Math.max have no prototype, and Object.create(undefined) throws.
  • Throw TypeError if this is not callable. Nice extras: name 'bound fn' and a reduced length.

The red pen

Common traps: mistake → fix

  • Mistake: Returning an arrow function from myBind

    Fix: new on the bound function throws TypeError.

  • Mistake: Using a string key like ctx.fn

    Fix: it can overwrite a real property; use a Symbol.

  • Mistake: boundFn.prototype = Object.create(fn.prototype) without a check

    Fix: crashes when binding Math.max or an arrow function (many published answers have this bug).

Easy to hard

Questions interviewers ask, easy to hard

  1. Write myCall without call or apply.
  2. Write myBind with partial arguments.
  3. Make new work with the bound function.
  4. What happens when you bind an arrow function or Math.max with your polyfill?
  5. Why a Symbol key? What about primitive ctx values and strict mode?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview