Sobes.tech
Middle+

Implement the Function.prototype.bind method — a function that takes a context and returns a new function with the bound context.

sobes.tech AI

Answer from AI

The bind function creates a new function with a fixed this context and, optionally, initial arguments. Here's an example implementation:

if (!Function.prototype.bind) {
  Function.prototype.bind = function(context, ...bindArgs) {
    const fn = this;
    return function(...callArgs) {
      return fn.apply(context, bindArgs.concat(callArgs));
    };
  };
}

Here, bind returns a new function that, when called, invokes the original function with the specified context and arguments.

Example usage:

const obj = {name: 'Alice'};
function greet(greeting) {
  return greeting + ', ' + this.name;
}
const boundGreet = greet.bind(obj);
console.log(boundGreet('Hello')); // Hello, Alice
Implement the Function.prototype.bind method — a… - sobes.tech