
在构造函数里使用 setinterval 时 this 指向的问题解答
在 javascript 中,构造函数内部的 this 指向实例对象。但是,在 setinterval 回调函数中,this 却指向 window 对象。这会导致 this 指向问题,导致无法访问实例对象的方法。
解决方法:
有两种方法可以解决此问题:
立即学习“Java免费学习笔记(深入)”;
- 使用 bind 方法:
// 创建构造函数
function myconstructor() {
this.circle = function() {...};
}
// 使用 bind 绑定 this
const _this = this;
setinterval(function() {
_this.circle();
}, 1000);- 使用箭头函数:
// 创建构造函数
function MyConstructor() {
this.circle = function() {...};
}
// 使用箭头函数保持 this 指向
setInterval(() => {
this.circle();
}, 1000);










