bind用于创建绑定this值并预置参数的新函数,返回函数不立即执行;可解决回调中this丢失问题,支持部分应用,但对箭头函数无效。

bind 是 JavaScript 中用于创建一个新函数的方法,它能固定(即“绑定”)原函数的 this 值,并可预先填入部分参数(称为“预置参数”或“柯里化”)。调用返回的新函数时,再传入剩余参数,最终执行原函数。
基本语法和预置参数效果
调用方式:func.bind(thisArg, arg1, arg2, ...)
-
thisArg:指定新函数执行时的this值(可为null或undefined,非严格模式下会指向全局对象) - 后续参数(
arg1, arg2...)会被“固定”为新函数的前几个实参 - 返回的是一个新函数,不会立即执行原函数
例如:
const add5 = add.bind(null, 5); // 预置第一个参数为 5
console.log(add5(10, 15)); // 输出 30(5 + 10 + 15)
绑定 this 并预置参数的常见场景
当方法需要作为回调(如事件监听、定时器、数组遍历)使用时,this 容易丢失。bind 可同时解决 this 和参数问题:
立即学习“Java免费学习笔记(深入)”;
const obj = {name: 'Alice',
greet: function(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
};
// 绑定 this 为 obj,并预置 greeting 为 'Hello'
const sayHello = obj.greet.bind(obj, 'Hello');
console.log(sayHello('!')); // "Hello, Alice!"
与箭头函数、call/apply 的区别
- bind 返回函数,call/apply 立即执行;bind 更适合“准备函数”,call/apply 适合“立刻调用”
- 箭头函数不绑定 this,也不能用 bind 改变其 this(bind 对箭头函数无效)
- bind 预置的参数不可撤销,但可在调用时追加更多参数(顺序拼接)
实用小技巧:模拟 partial(部分应用)
虽然 ES6+ 推荐用箭头函数或工具库(如 Lodash 的 partial),但 bind 是原生轻量方案:
const divideBy100 = (x) => x / 100;
// 等价写法(更显式地体现预置):
const divideBy100Bind = (function(divisor, dividend) {
return dividend / divisor;
}).bind(null, 100); // 预置 divisor = 100
console.log(divideBy100Bind(500)); // 5


















