观察这段代码。
function adder(a, b) {
return a + b;
}
const adderFive = adder.bind(null, 5);
let pauloAgeInFuture = adderFive(41, 1) //
console.log(pauloAgeInFuture); //->46
console.log(adderFive(5, 10)); //->10
第2个参数被忽略的原因是:1)因为使用null,我说绑定的值(5)是默认的b arg,还是2)因为传递了5作为参数,我说函数正在等待另外一个参数(第一个被传递的)?
为什么必须使用null才能得到这个结果(如果我这样做的话 const adderFive = adder.bind(5);
函数接受2个参数,并忽略5的值(我想)。
谢谢你
的第一个参数 bind()
是 this
的上下文,当调用该函数时,将提供该上下文。由于你的函数没有使用 this
在你的例子中,这个参数会被忽略。
其余的参数会被插入到参数列表的前面,后面是传递给绑定函数的任何参数。所以当你调用
adderFive(41, 1)
无异于
adder(5, 41, 1)
adder
只使用前两个参数,所以这将返回 5 + 41
.