显式绑定规则指通过call、apply或bind手动指定函数执行时this的指向,是四种this绑定规则中最直接可控的;call和apply立即执行并传参,bind返回永久绑定this的新函数,且显式绑定优先级高于隐式绑定,但对箭头函数无效。

在 JavaScript 中,显式绑定规则指的是通过 call、apply 或 bind 方法,**手动指定函数执行时内部 this 的指向**。这是四种 this 绑定规则(默认、隐式、显式、new)中最直接可控的一种。
用 call 和 apply 强制指定 this
call 和 apply 都会立即执行函数,并把第一个参数作为 this 值传入。区别只在于后续参数的传递方式:
-
func.call(thisArg, arg1, arg2, ...)—— 参数逐个列出 -
func.apply(thisArg, [arg1, arg2, ...])—— 参数以数组形式传入
例如:
const person = { name: 'Alice' };
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
greet.call(person, 'Hello', '!'); // "Hello, Alice!"
greet.apply(person, ['Hi', '.']); // "Hi, Alice."
用 bind 创建永久绑定的新函数
bind 不会立即执行函数,而是返回一个**新函数**,该函数内部的 this 被永久绑定为 bind 的第一个参数,后续参数也会被预置(柯里化)。
立即学习“Java免费学习笔记(深入)”;
即使新函数 later 在不同上下文中被调用(比如作为回调、事件处理器),this 也不会改变:
const obj = { value: 42 };
function logThis() {
console.log(this.value);
}
const boundFn = logThis.bind(obj);
boundFn(); // 42
setTimeout(boundFn, 100); // 仍输出 42,不会丢失 this
显式绑定优先级高于隐式绑定
当一个函数既通过对象属性调用(隐式绑定),又被 call/apply/bind 调用时,显式绑定生效,隐式绑定被忽略:
const obj = { name: 'Bob', method: function() { return this.name; } };
const anotherObj = { name: 'Charlie' };
obj.method(); // "Bob"(隐式绑定)
obj.method.call(anotherObj); // "Charlie"(显式覆盖隐式)
obj.method.bind(anotherObj)(); // "Charlie"
注意:箭头函数无法被显式绑定
箭头函数没有自己的 this,它会沿作用域链向上查找外层普通函数的 this。因此 call、apply、bind 对其无效:
const obj = { name: 'David' };
const arrow = () => this.name;
arrow.call(obj); // 仍返回外层 this.name(通常为 undefined 或全局对象)


















