推荐答案
function myBind(fn, context, ...args) {
return function(...innerArgs) {
return fn.apply(context, [...args, ...innerArgs]);
};
}本题详细解读
1. 函数签名
myBind(fn, context, ...args) 是一个自定义的 bind 函数,它接受三个参数:
fn: 需要绑定的函数。context: 绑定函数的this上下文。...args: 传递给绑定函数的初始参数列表。
2. 返回值
myBind 返回一个新的函数,这个新函数在被调用时会将 context 作为 this 上下文,并将 args 和调用时传入的参数合并后传递给原函数 fn。
3. 实现细节
- 闭包:
myBind返回的函数是一个闭包,它捕获了fn、context和args这些外部变量。 - 参数合并: 在返回的函数中,
...innerArgs是调用时传入的参数,它们与args合并后传递给fn。 - apply 方法: 使用
apply方法将context作为this上下文,并将合并后的参数传递给fn。
4. 示例用法
// www.javascriptcn.com code example
const obj = {
value: 42
};
function printValue(a, b) {
console.log(this.value + a + b);
}
const boundPrint = myBind(printValue, obj, 10);
boundPrint(20); // 输出: 72 (42 + 10 + 20)在这个示例中,boundPrint 是一个绑定了 obj 作为 this 上下文的函数,并且 10 作为初始参数传递给了 printValue。当调用 boundPrint(20) 时,20 作为第二个参数传递给 printValue,最终输出 72。