FrontendInterviews.dev

Loading problem…

39. Function.prototype.bind

Medium•
Acceptance: 54.17%
•
🔓3/3 Pro unlocks today

Implement your own version of Function.prototype.bind method. The bind method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Requirements

1. Basic Functionality

  • Accept a thisArg parameter to be used as the this value
  • Accept optional pre-filled arguments (partial application)
  • Return a new function (not call the original)
  • The returned function should preserve the bound context and arguments

2. Edge Cases

  • Handle null or undefined as thisArg (should default to global object)
  • Support partial application (pre-filled arguments)
  • Support additional arguments when calling the bound function
  • Handle new operator on bound functions (constructor calls)
  • Preserve function properties (like length)

Example Usage

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const person = { name: 'Alice' };

// Using built-in bind
const boundGreet = greet.bind(person, 'Hello');
boundGreet('!'); // "Hello, Alice!"

// Using your implementation
const myBoundGreet = greet.myBind(person, 'Hello');
myBoundGreet('!'); // "Hello, Alice!"

Constraints

  • Must return a new function, not call the original
  • Handle edge cases: null/undefined thisArg, partial application
  • Should not use Function.prototype.bind internally
  • Support additional arguments when calling the bound function
  • Bound function should work with 'new' operator
  • Preserve function context and arguments correctly