[英]Pass “this” into window.setInterval()
I have code that looks like this: 我有看起来像这样的代码:
var X = {
updateAll: function() {
// ...
},
init: function() {
window.setInterval(function() {
this.updateAll();
}, 40000);
}
}
In X.init()
, I want to be able to access updateAll()
, but for obvious reasons it does not work as intended. 在
X.init()
,我希望能够访问updateAll()
,但是由于明显的原因,它无法按预期工作。
How can I achieve the required outcome? 如何获得所需的结果?
init: function() {
var _self = this;
window.setInterval(function() {
_self.updateAll();
}, 40000);
}
you can do it this way. 你可以这样
var X = {
updateAll: function() {
console.log('updateALL');
},
init: function() {
var self=this;
window.setTimeout(function() {
self.updateAll();
}, 200);
}
};
You can bind the function: 您可以绑定函数:
init: function() {
window.setInterval(function() {
this.updateAll();
}.bind(this), 40000);
}
Or, if you are using ECMAScript 2015, you can use an arrow function: 或者,如果您使用的是ECMAScript 2015,则可以使用箭头功能:
init: function() {
window.setInterval(() => {
this.updateAll();
}, 40000);
}
You can use the var self = this
method as mentioned in other answers, OR you can use the .bind method that functions have: 您可以使用
var self = this
方法在其他的答案中提到, 或者你可以使用的功能有.bind方法:
var X = {
updateAll: function() {
// ...
},
init: function() {
window.setInterval(
this.updateAll.bind(this),
40000
);
}
}
Please note that you don't need all that "function() {...}" in the first argument to setInterval -- it's redundant. 请注意,在setInterval的第一个参数中并不需要所有的“ function(){...}”-这是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.