我有一个 Javascript 对象,它试图从方法中的 setInterval() 内部访问本地属性,但显然因为它试图调用 setInterval 中函数的本地范围,所以本地属性是返回未定义。代码如下:
function Timer() {
this.remaining = 15000;
}
Timer.prototype.start = function() {
this.refreshId = setInterval(function() {
console.log(this.remaining);
},1000);
}
如何访问本地“剩余”变量?谢谢!
最佳答案
function Timer() {
this.remaining = 15000;
}
Timer.prototype.start = function() {
var that = this;
this.refreshId = setInterval(function() {
//this.adjust(-1000);
that.remaining -= 1000;
console.log(that.remaining);
if (that.remaining <= 0) {
that.remaining = 0;
that.status = 'paused';
clearInterval(that.refreshId);
}
},1000);
}
setInterval 函数在全局范围内调用。因此,您可以将“this”缓存为不同的变量(例如,作为“that”,这在开发人员中很常见。)
另一种选择是提出一个 .bind 函数或方法,您可以通过搜索 Google 来了解如何操作。
阅读:Understanding Javascript Closures with Ease
关于javascript - 从内部函数访问本地对象属性(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808439/