bind 是函数特有的一个方法,可以创建一个绑定了 this 的新函数。
function Class1() {
this.name = "Tom";
this.showName = function (pre) {
console.log(pre + this.name);
};
}
c1 = new Class1();
c1.showName("A"); // ATom
function Class2() {
this.name = "Jack";
}
c2 = new Class2();
let res = c1.showName.bind(c2, "B");
res("C"); // BJack
倒数第二行可以看到bind返回的是一个函数,绑定了this的新函数。且当我们调用它并且再传额外的参数“C”的时候没有报错,这就是bind函数另一个用的比较少的作用:积累参数(函数柯里化)。
·创建一个绑定了this的新函数
·积累参数
实现一个bind:
Function.prototype.myBind = function (thisArg, ...prefixArgs) {
const fn = this;
return function (...args) {
return fn.call(thisArg, ...prefixArgs, ...args);
};
};
要点是利用 闭包。
让返回的新函数可以访问到三个私有属性:
-
fn(原来的函数)
-
thisArg(需要强绑不变的 this 指向)
-
prefixArgs 属性
当我们调用这个新函数时,我们会执行 fn 函数,并利用 call 方法来指定 this 为 thisArg,然后将预填充的多个参数,和新函数接收的参数依次填入。