Files
30-seconds-of-code/snippets/bind.md
Angelos Chalaris 8a6b73bd0c Update covers
2023-02-16 22:24:28 +02:00

830 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Bind function context function,object tranquility 2018-01-24T14:14:49+02:00 2020-10-18T23:04:45+03:00

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!'