Creates a function that invokes fn
with a given context, optionally prepending any additional supplied parameters to the arguments.
- Return a
function
that usesFunction.prototype.apply()
to apply the givencontext
tofn
. - 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!'
翻译自:https://www.30secondsofcode.org/js/s/bind-function-context