Bind function context

JavaScript, Function, Object · Oct 18, 2020

Creates a function that invokes fn with a given context, optionally prepending any additional supplied parameters to the arguments.

  • Return a function that uses Function.prototype.apply() to apply the given context to fn.
  • Use the spread operator (...) to prepend any additional supplied parameters to the arguments.
const bind = (fn, context, ...boundArgs) => (...args) =>
  fn.apply(context, [...boundArgs, ...args]);
function greet(greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
}
const freddy = { user: 'fred' };
const freddyBound = bind(greet, freddy);
console.log(freddyBound('hi', '!')); // 'hi fred!'

More like this

  • Bind object method

    Creates a function that invokes the method at a given key of an object, optionally prepending any additional supplied parameters to the arguments.

    JavaScript, Function · Oct 18, 2020

  • Prepend function arguments

    Creates a function that invokes fn with partials prepended to the arguments it receives.

    JavaScript, Function · Sep 15, 2020

  • Append function arguments

    Creates a function that invokes fn with partials appended to the arguments it receives.

    JavaScript, Function · Sep 15, 2020