741 B
741 B
title, tags
| title | tags |
|---|---|
| bind | function,object,intermediate |
Creates a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
- Return a
functionthat usesFunction.prototype.apply()to apply the givencontexttofn. - Use
Array.prototype.concat()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!'