构造函数定义的类属性为何在setInterval回调中输出undefined
异常根因
你遇到的this.timeElapsed输出undefined,本质是回调场景下的this指向丢失:
在startDelayTimer方法中,给setInterval传入的是this.calculateDelayTime独立函数引用,没有和当前ReactionTimer类实例建立绑定。当定时器触发回调时,函数内部的this会遵循定时器的默认规则指向全局window对象,而非当前类实例。此时在calculateDelayTime内访问this.timeElapsed,实际是在读取window对象上的同名属性,这个属性从未被定义,自然输出undefined。
修复方案
- 最简便的修改:把传入
setInterval的回调替换为箭头函数包裹,利用箭头函数不绑定自身this的特性,直接继承外层作用域的this指向。将原有代码:
修改为:this.timer = setInterval(this.calculateDelayTime, 10);this.timer = setInterval(() => this.calculateDelayTime(), 10); - 等价实现:通过
bind方法将函数的this硬绑定到当前实例,同样替换上述setInterval代码:this.timer = setInterval(this.calculateDelayTime.bind(this), 10); - 全局适配方案:如果希望后续所有调用
calculateDelayTime的场景都不会出现this丢失问题,可以在类的构造函数中提前完成绑定:constructor() { this.timeTotal = Math.floor(Math.random() * 301) * 10; this.timeElapsed = 0; // 提前为方法绑定固定的this指向 this.calculateDelayTime = this.calculateDelayTime.bind(this); }
注意:你代码中后续定义的箭头函数(1ms间隔的精确计时回调、document.onkeydown的按键回调)本身没有this指向问题,只要修复首次传入setInterval的函数引用的this绑定,整个反应计时逻辑就可以正常运行。
内容的提问来源于stack exchange,提问作者BrianZhang
相关产品推荐
相关产品推荐

