javascript 中的箭头函数不支持 call、apply 和 bind 来改变其内部的 this 指向。这些方法虽然存在于箭头函数的原型链上,但调用时不会生效,因为箭头函数没有自己的 this 绑定,它始终捕获定义时所在作用域的 this 值。

为什么 call 无法改变箭头函数的 this
使用 call 方法调用箭头函数时,第一个参数会被忽略,函数体内的 this 依然保持定义时的上下文。这是因为箭头函数在语法层面被设计为“词法”的 this,它不创建新的执行上下文,因此无法像普通函数那样通过调用机制动态绑定 this。

const obj = { name: 'Object', getValue: () => this.name };
// 尝试用 call 改变 this
const result = obj.getValue.call({ name: 'Changed' });
console.log(result); // 输出 undefined 或全局对象属性,而非 'Changed'在上述代码中,getValue 是一个箭头函数。当调用 obj.getValue.call({ name: 'Changed' }) 时,传入的对象 { name: 'Changed' } 被完全忽略。this 仍然指向定义该箭头函数时的作用域(通常是模块级或全局对象),因此无法获取到预期对象的属性。
立即学习“Java免费学习笔记(深入)”;
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
为什么 bind 也无法实现永久绑定
使用 bind 方法作用于箭头函数时,返回的新函数依然不会接受任何 this 绑定。即使你显式地绑定了某个对象,调用该新函数时,内部的 this 依然是原始定义时的环境。这与普通函数不同,普通函数通过 bind 可以创建一个 this 固定的新函数。

const arrowFunc = () => console.log(this);
// 尝试用 bind 绑定 window
const boundFunc = arrowFunc.bind(window);
// 无论怎么调用,this 都是定义时的环境
boundFunc();
arrowFunc.call({});
arrowFunc.apply({});这段代码展示了 bind 对箭头函数的无效性。无论是否使用 bind、call 还是 apply,arrowFunc 内部的 this 始终一致。这种行为确保了箭头函数在作为回调函数传递时,其上下文始终保持稳定,不会因为调用方式的变化而意外改变。
箭头函数在不同作用域下的 this 表现
为了验证箭头函数 this 的词法特性,我们可以观察它在嵌套函数中的表现。当箭头函数定义在普通函数内部时,它会捕获外部普通函数的 this;当定义在全局或模块顶层时,它捕获全局或模块的 this。这种机制使得箭头函数非常适合用于需要保持上下文一致性的场景,如事件处理或异步回调。
function RegularFunction() {
this.value = 42;
const arrow = () => console.log(this.value);
return arrow;
}
const instance = new RegularFunction();
const getter = instance.getValue || RegularFunction.prototype.getValue; // 假设我们提取了箭头函数
// 更直接的测试:
const testObj = {
id: 'test',
getArrow: () => this.id,
getRegular: function() { return this.id }
};
console.log(testObj.getArrow()); // undefined (this 指向全局/模块)
console.log(testObj.getRegular()); // 'test' (this 指向 testObj)运行上述代码,getArrow 返回 undefined,因为它定义在 testObj 字面量中时,其 this 并没有绑定到 testObj,而是外层作用域。相比之下,getRegular 正确返回了 'test'。这进一步证实了箭头函数无法通过对象方法调用的形式来改变 this,它只认定义时的环境。

















