JavaScript使用setInterval调用类方法出现this.entities未定义如何解决
问题原因
你遇到的报错是典型的类方法this绑定丢失问题:当你直接把newGame.update作为回调传给setInterval时,update方法的执行上下文会被切换为全局作用域(浏览器环境下为window,严格模式下为undefined),不再指向newGame实例,自然找不到this.entities属性。
用bind的解决方法
bind方法可以永久绑定函数的this指向,你只需要修改setInterval的传参即可:
let t = setInterval(newGame.update.bind(newGame), 1000);
上述代码会将update方法的this强行绑定到newGame实例,每次定时器触发执行时,this都会正确指向实例,就能正常读取this.entities和this.context属性。
其他常用替代方案
如果你不想每次调用都写bind,也可以选以下两种方案:
- 用箭头函数包裹回调,箭头函数会继承外层作用域的
this指向,无需手动绑定:let t = setInterval(() => newGame.update(), 1000); - 在类的构造函数中预先绑定
update方法的this,后续直接传方法即可:class Game { constructor() { this.gameOver = false; this.entities = []; this.context = document.getElementById("canvas").getContext("2d"); // 预先绑定this到实例 this.update = this.update.bind(this); } // 其余代码不变 } // 后续调用setInterval时不需要额外处理 let t = setInterval(newGame.update, 1000);
内容的提问来源于stack exchange,提问作者Robin Konold
相关产品推荐
相关产品推荐

