bind 基本使用:
function test() {
name = 'test';
console.log('[result]', this.name);
}
const a = {
name: 'a',
}
test();
const res = test.bind(a);
res();
//[result] test
//[result] a
当使用 Function.prototype.bind
方法时,它会创建一个新函数,该函数的 this
值被绑定到指定的上下文(ctx
),并且部分参数被预先设置。
下面是一个简单的 JavaScript 模拟实现:
Function.prototype.myBind = function(ctx, ...args) {
const fn = this; // 当前函数
return function(...newArgs) {
return fn.apply(ctx, args.concat(newArgs));
};
};
让我解释一下这个模拟实现的关键部分:
myBind
方法是定义在Function.prototype
上的,这样可以在所有函数对象上使用。- 在
myBind
方法内部,我们首先保存了当前函数的引用,即this
。 - 返回一个新函数,这个新函数接受任意数量的参数
newArgs
。 - 当调用新函数时,它会调用原始函数
fn
,并将ctx
作为this
值,以及绑定的参数args
和新传入的参数newArgs
。 - 使用
apply
方法来确保函数在指定的上下文中执行,并传递正确的参数。
这样,调用 myBind
方法就会返回一个新函数,该新函数的 this
值被绑定到指定的上下文,并且部分参数被预先设置。