【问题标题】:Does null set a default argument in a bound function, with JS bind?null 是否在绑定函数中设置默认参数,使用 JS 绑定?
【发布时间】:2020-09-25 04:16:14
【问题描述】:

观察这段代码:

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

第二个参数是否被忽略,因为 1) 因为使用 null 我说绑定值 (5) 是默认的 b arg,或者 2) 因为传递 5 作为参数我说函数正在等待到另一个参数(第一个被传递)?

【问题讨论】:

  • bind() 的第一个参数是 this 上下文。

标签: javascript function functional-programming bind


【解决方案1】:

bind() 的第一个参数是调用函数时将提供的this 上下文。由于您的函数不使用this,因此在您的示例中此参数将被忽略。

其余的参数被插入到参数列表的前面,然后是传递给绑定函数的任何参数。所以当你打电话时

adderFive(41, 1)

相当于调用

adder(5, 41, 1)

adder 仅使用前两个参数,因此返回 5 + 41

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多