需保存this因定时器回调异步独立执行,默认this指向全局对象;常用方式:缓存为self/that变量、使用箭头函数(自动继承外层this)或bind(this)。

在 JavaScript 定时器(如 setTimeout 或 setInterval)中,回调函数默认运行在全局上下文里,this 通常指向 window(浏览器)或 globalThis(Node.js),而不是你期望的调用对象。所以,**需要提前把当前的 this 保存为一个变量**,才能在定时器回调中正确访问。
为什么需要保存 this
因为定时器回调是“异步独立调用”的,它不继承外层函数的执行上下文。比如在对象方法里写 setTimeout(function() { console.log(this); }, 100),里面的 this 就不再是该对象,而是全局对象。
常用保存方式:用 const/let 变量缓存
在进入定时器前,用一个变量(如 self、that 或更语义化的名字)保存当前 this:
- ✅ 推荐写法(清晰、兼容性好):
const self = this;<br>setTimeout(function() {<br> console.log(self.name); // 正确访问实例属性<br>}, 100);
立即学习“Java免费学习笔记(深入)”;
- ✅ 箭头函数(更简洁,自动绑定 this):
setTimeout(() => {<br> console.log(this.name); // 箭头函数继承外层 this<br>, 100);
- ⚠️ 注意:
bind(this)也可用,但不如前两种直观:
setTimeout(function() {<br> console.log(this.name);<br>}.bind(this), 100);
在类方法中典型场景
比如 Vue 或普通 class 中启动定时器:
class TimerController {<br> constructor() {<br> this.count = 0;<br> }<br> start() {<br> const self = this; // ← 关键:缓存 this<br> this.timer = setInterval(function() {<br> self.count++; // ✅ 能访问实例属性<br> console.log(self.count);<br> }, 1000);<br> }<br>}
避免常见错误
- 不要直接在
setTimeout(function() { ... })里用this,除非你明确知道它的指向 - 不要在箭头函数外层再套普通函数并期望
this传递(会断掉) - 如果用
call/apply手动指定this,要确保传入的是正确的对象引用


















