Q12: Write a Custom Function.prototype.bind Polyfill

Implement a custom version of Function.prototype.bind that captures context and initial bound arguments, returning a function that accepts additional arguments at call time.

Function bind Polyfill
Function.prototype.myBind = function(context, ...boundArgs) {
  const fn = this;
  if (typeof fn !== 'function') {
    throw new TypeError('Bind must be called on a function');
  }
  return function(...args) {
    return fn.apply(context, [...boundArgs, ...args]);
  };
};

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}
const bound = greet.myBind({ name: 'Alex' }, 'Hello');
console.log(bound('!')); // 'Hello, Alex!'
💡 myBind returns a wrapper that applies the stored context and combines initial boundArgs with invocation arguments.
Key Takeaways
  • Captures this target function inside a closure.
  • Concatenates initial boundArgs with execution call args during invocation.
Knowledge Check

How are initial arguments passed to myBind merged with arguments passed to the bound execution function?