810 B
810 B
title, type, tags, cover, dateModified
| title | type | tags | cover | dateModified | ||
|---|---|---|---|---|---|---|
| Bind function context | snippet |
|
tranquility | 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
functionthat usesFunction.prototype.apply()to apply the givencontexttofn. - 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!'