
在构造函数里使用 setinterval 时 this 指向的问题解答
在 javascript 中,构造函数内部的 this 指向实例对象。但是,在 setinterval 回调函数中,this 却指向 window 对象。这会导致 this 指向问题,导致无法访问实例对象的方法。
解决方法:
有两种方法可以解决此问题:
立即学习“Java免费学习笔记(深入)”;
// 创建构造函数
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 指向问题如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号