HomePremium · ₹1199
← All questions

Implement Function.prototype.call (myCall)

Medium
Asked at:AmazonFlipkart
Was this asked in an interview?

Write myCall(fn, thisArg, ...args) — invoke a function with an explicit this and individual arguments.

Problem

Implement myCall(fn, thisArg, ...args) — a standalone version of Function.prototype.call.

call lets you borrow a function and run it with a this of your choosing, passing arguments individually. This is how you reuse methods across unrelated objects (e.g. running an array method on an array-like arguments object).

Your myCall(fn, thisArg, ...args) must:

  • Invoke fn with its this set to thisArg.
  • Forward the remaining args to fn individually.
  • Return whatever fn returns.
  • Not permanently mutate thisArg (clean up any temporary property you add).

Input

function greet(greeting) {
  return `${greeting}, ${this.name}`;
}
myCall(greet, { name: "Alice" }, "Hi");

Expected output

"Hi, Alice"

Implement from scratch (don't use the built-in call/apply/bind):

function myCall(fn, thisArg, ...args) {
  // Your code here
}
Implement Function.prototype.call (myCall) — JavaScript Interview Question | Mentoxis