箭头函数能自动绑定外层作用域的this,避免手动保存this;因普通函数中this取决于调用方式,在回调中易丢失,故需self=this;箭头函数继承外层this,天然适配保持实例上下文,但不可用于构造函数、对象方法或原型方法。

箭头函数能自动绑定外层作用域的 this,从而避免手动写 self = this 或 that = this 的冗余操作。
为什么需要 self = this?
在普通函数中,this 的指向取决于调用方式,而非定义位置。当把方法作为回调传入异步操作(如 setTimeout、addEventListener、Promise.then)时,this 会丢失,变成 undefined(严格模式)或全局对象。为保留原始上下文,开发者常提前保存:const self = this;
然后在回调里用 self.xxx 访问实例属性或方法。
箭头函数如何替代 self = this?
箭头函数不绑定自己的 this,而是继承外层函数作用域的 this 值——这个特性天然适配“保持当前实例上下文”的需求。
- 把原本用
function() { ... }写的回调,直接改成() => { ... } - 确保箭头函数定义在希望继承
this的作用域内(比如类的方法体、构造函数中) - 注意:不能用箭头函数定义对象方法或原型方法,因为它没有
this绑定能力,无法被正确调用
常见场景对比示例
传统写法(需 self):
class Timer {
constructor() {
this.count = 0;
}
start() {
const self = this;
setInterval(function() {
self.count++; // 必须用 self,否则 this 指向 setInterval 全局
console.log(self.count);
}, 1000);
}
}
箭头函数写法(无需 self):
class Timer {
constructor() {
this.count = 0;
}
start() {
setInterval(() => {
this.count++; // 直接访问 this,指向 Timer 实例
console.log(this.count);
}, 1000);
}
}
需要注意的边界情况
箭头函数虽好,但不是万能解药:
- 不能用作构造函数(没有
prototype,调用new会报错) - 没有
arguments对象,要用 rest 参数(...args)替代 - 在事件监听器中若需访问事件对象或
event.target,仍要通过参数接收,和this无关 - 如果外层作用域的
this本身就不对(比如函数被错误调用),箭头函数也会继承错误的this
不复杂但容易忽略。

















