程序开发 · 2025年3月26日

JavaScript 构造函数中 setInterval 的 this 指向问题如何解决?

在构造函数里使用 setinterval 时 this 指向的问题解答

在 javascript 中,构造函数内部的 this 指向实例对象。但是,在 setinterval 回调函数中,this 却指向 window 对象。这会导致 this 指向问题,导致无法访问实例对象的方法。

解决方法:

有两种方法可以解决此问题:

立即学习“”;

  • 使用 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);

登录后复制

以上就是JavaScript 构造函数中 setInterval 的 this 指向问题如何解决?的详细内容,更多请关注GTHOST其它相关文章!