call, apply & bind: Interview Must-Knows
JS جاوااسکریپت

call, apply & bind: Interview Must-Knows

Explicitly set `this` and partially apply arguments — foundational for understanding JavaScript functions.

BugCast Admin··۵ دقیقه مطالعه

Every function inherits call, apply, and bind from Function.prototype. They let you control this and arguments — critical for borrowing methods and fixing callbacks.

Common Interview Questions

Q: Difference between call and apply?

Answer: call invokes with this and arguments listed individually. apply takes an array-like of arguments. Both invoke immediately.


fn.call(obj, 1, 2);
fn.apply(obj, [1, 2]);

Q: Implement a simple bind

Answer: Return a wrapper that calls the original with bound this and merged arguments. Production bind also handles new for constructor functions.


Function.prototype.myBind = function (context, ...partial) {
  const fn = this;
  return function (...args) {
    return fn.apply(context, [...partial, ...args]);
  };
};

Q: Borrowing array methods on array-like objects

Answer: Before spread, Function.prototype.call let you use array methods on arguments or NodeList objects.


const args = { 0: "a", 1: "b", length: 2 };
Array.prototype.slice.call(args);

Q: Can bound functions be used with new?

Answer: Yes — if the original is a constructor, new boundFn() creates an instance ignoring the bound this for new semantics. Rare but worth mentioning at senior level.

Key Points for Interviews

  • All three set this explicitly

  • Only bind returns a new function without calling

  • Arrow functions cannot be bound — they ignore this argument

  • Polyfills and legacy codebases use apply heavily

  • Modern alternative: arrow wrappers for lexical this

#call#apply#bind#interview

مطالب مرتبط