我如何更改“this"的范围?在 setInterval 和 setTimeout 函数中 [英] How do I change scope of "this" in setInterval and setTimeout functions
本文介绍了我如何更改“this"的范围?在 setInterval 和 setTimeout 函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 setInterval
和 setTimeout
调用中使用 this
?
How is it possible to use this
inside of setInterval
and setTimeout
calls?
我想像这样使用它:
function myObj() {
this.func = function(args) {
setTimeout(function() {
this.func(args);
}, 1000);
}
}
前段时间我是这样为 .onclick
事件做的:
Some time ago I did it for .onclick
event this way :
this.click = function(func) {
this.elem.onclick = (function(func, obj) {return function(){func.apply(obj)} })(func,this);
};
但我不知道如何为 intervals
和 timeouts
做到这一点.
but I don't know how I can do it for intervals
and timeouts
.
推荐答案
最简单的方法是将 this
保存到本地.本地 self
不会被调用 setInterval
和 setTimeout
回调的上下文改变.它将改为保持原始的 this
值
The easiest way is to just save this
into a local. The local self
isn't changed by the context in which setInterval
and setTimeout
callbacks are invoked. It will instead maintain the original this
value
function myObj() {
var self = this;
this.func = function(args) {
setTimeout(function() {
self.func(args);
}, 1000);
}
}
这篇关于我如何更改“this"的范围?在 setInterval 和 setTimeout 函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文