bind方法返回新函数,固定this值并预设左侧参数,调用时参数追加在预设参数之后;不可被call/apply覆盖this,箭头函数无法用bind改变this。

bind 方法可以固定函数的 this 值,并预设部分参数,返回一个新函数(不立即执行)。它常用于“参数柯里化”或绑定上下文,特别适合事件处理、回调传参等场景。
基础用法:绑定 this 和前几个参数
调用 fn.bind(thisArg, arg1, arg2, ...) 会返回一个新函数。当这个新函数被调用时:
- 它的
this指向thisArg(即使后续用call/apply也无法覆盖) - 调用时传入的参数会**追加在预设参数之后**
示例:
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
<p>const person = { name: 'Alice' };
const sayHello = greet.bind(person, 'Hello'); // 预设 this 和第一个参数</p><p>sayHello('!'); // "Hello, Alice!"
sayHello('?'); // "Hello, Alice?"
预设多个参数,留空后面参数
bind 支持预设任意数量的参数,未预设的参数在调用新函数时再传入。
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
立即学习“Java免费学习笔记(深入)”;
示例:预设前两个参数,第三个留到运行时
function multiply(a, b, c) {
return a * b * c;
}
<p>const double = multiply.bind(null, 2, 1); // a=2, b=1,c 待定
double(5); // 2 <em> 1 </em> 5 = 10</p><p>const triple = multiply.bind(null, 3); // a=3,b 和 c 待定
triple(4, 6); // 3 <em> 4 </em> 6 = 72
与箭头函数、call/apply 的关键区别
-
bind 返回函数,不执行;
call/apply立即执行 -
bind 绑定的 this 不可被后续 call/apply 覆盖(除非 bind 时传的是
null或undefined,且非严格模式下会被自动替换为全局对象) - 箭头函数没有自己的 this,不能用 bind 改变其 this —— 它始终继承外层作用域的 this
实用技巧:模拟 partial(部分应用)
虽然 bind 只能从左到右预设参数,但可配合占位符思路(如用 null 占位)实现更灵活的预设(需手动封装):
// 简单的 left-partial 封装(类似 Lodash 的 partial)
function partial(fn, ...presetArgs) {
return function(...laterArgs) {
const args = [];
let presetIndex = 0;
for (const arg of presetArgs) {
if (arg === undefined) {
args.push(laterArgs.shift());
} else {
args.push(arg);
}
}
return fn.apply(this, args.concat(laterArgs));
};
}
<p>// 使用:让第二个参数先空着
const add5 = partial((a, b, c) => a + b + c, 5, undefined, 10);
add5(3); // 5 + 3 + 10 = 18
不过原生 bind 更轻量、性能更好,日常预设左侧参数完全够用。

















