bind() 通过返回一个绑定了指定 this 的新函数来改变指向,调用该新函数时内部 this 将固定为传入的第一个参数。

bind() 返回的函数如何执行
bind() 不会立即执行原函数,而是生成一个全新的函数对象。这个新函数在后续被调用时,会忽略任何手动绑定的 this(如 call 或 apply),始终使用 bind 时指定的值。

function greet() {
console.log('Name:', this.name);
}
const obj = { name: 'Alice' };
// 创建绑定函数
const boundGreet = greet.bind(obj);
// 执行绑定后的函数
boundGreet(); // 输出: Name: Alice
// 尝试强行修改 this,无效
boundGreet.call({ name: 'Bob' }); // 依然输出: Name: Alice部分应用参数与 bind() 的结合
bind() 除了绑定 this,还可以预设部分参数。当调用返回的新函数时,传入的参数会追加到预设参数之后,形成完整的参数列表传递给原函数。
立即学习“Java免费学习笔记(深入)”;

function add(a, b, c) {
return a + b + c;
}
// 绑定 this 为 null,并预设第一个参数为 10
const partialAdd = add.bind(null, 10);
// 调用时传入剩余参数
console.log(partialAdd(5, 2)); // 输出: 17 (10 + 5 + 2)基于 bind() 返回函数的柯里化效果
利用 bind() 可以模拟简单的柯里化行为。每次调用 bind() 都会锁定当前的 this 和部分参数,生成的新函数保留了这些状态。如果多次链式调用 bind(),后一次调用无法覆盖前一次已锁定的 this,但可以增加新的预设参数。


















