碎片时间学编程「342]:绑定函数上下文

创建一个使用给定上下文调用 fn 的函数,可以选择将任何额外提供的参数添加到参数中。 返回一个函数,该函数使用 Function.prototype.apply() 方法将给定的上下文应用到 fn。 使用扩展运算符 (...) 将任何额外提供的参数添加到参数中。
JavaScript
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.icoderoad.com