bind方法创建新函数并永久绑定this,不执行原函数;与call/apply的临时绑定不同,其this无法被后续调用覆盖,且多次bind仅首次生效。

bind 方法能创建一个新函数,把原函数的 this 永久绑定到指定对象上,之后无论怎么调用,this 都不会变。它不执行原函数,只返回一个“绑定好 this”的新函数,适合需要稳定上下文的场景,比如事件回调、定时器、传参复用等。
基本用法:绑定 this 并可预设参数
语法是 fn.bind(thisArg, arg1, arg2, ...)。第一个参数是希望 this 指向的对象,后面是可选的预置参数。
例如:
const obj = { name: 'Alice' };function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const boundGreet = greet.bind(obj, 'Hello'); // this 固定为 obj,且第一个参数固定为 'Hello'
console.log(boundGreet('!')); // "Hello, Alice!"
console.log(boundGreet('?')); // "Hello, Alice?"
为什么叫“永久”锁定?和 call/apply 的区别
call 和 apply 是立即执行,并临时指定 this;bind 不执行,而是生成一个新函数,其内部 this 被硬编码(hard-coded),无法被后续调用方式覆盖。
立即学习“Java免费学习笔记(深入)”;
- 即使用
obj.method.bind(otherObj)()再加括号调用,this 仍是otherObj - 即使赋值给变量后在全局环境调用:
const f = obj.method.bind(otherObj); f();,this 还是otherObj - 箭头函数没有自己的 this,所以 bind 对它无效(它会忽略 bind 的第一个参数)
常见实用场景
✅ 事件处理器中保持 this:
在类方法中绑定事件时,避免 this 指向 DOM 元素或 undefined。
constructor() {
this.label = 'Click me';
this.element = document.getElementById('btn');
this.element.addEventListener('click', this.handleClick.bind(this));
}
handleClick() {
console.log(this.label); // 正确输出 'Click me'
}
}
✅ 配合 setTimeout/setInterval 避免 this 丢失:
直接传 obj.method 会导致 this 变成全局对象或 undefined(严格模式下)。
count: 0,
start() {
setInterval(this.tick.bind(this), 1000); // ✅ this 始终是 timer
}
tick() {
this.count++;
console.log(this.count);
}
};
小提醒:bind 后还能再 bind 吗?
可以,但只有第一次 bind 生效。多次 bind 不会改变已绑定的 this —— 后续 bind 的 this 参数会被忽略。
function foo() { return this.value; }const obj1 = { value: 1 };
const obj2 = { value: 2 };
const bound1 = foo.bind(obj1);
const bound2 = bound1.bind(obj2); // 无效!this 仍是 obj1
console.log(bound1()); // 1
console.log(bound2()); // 1(不是 2)


















