Javascript this 对象在间隔/超时内
我有一个方法,它是一个很大的 setInterval 语句,它需要从间隔内部访问拥有该方法的对象的 this 对象。我实现了一个简单的闭包,但它看起来不太优雅:
connect: function(to, rate, callback){
var cthis = this, //set cthis to this,
connectIntervalID = setInterval(function(){
if(cthis.attemptConnect(to)){ //reference it here,
clearInterval(connectIntervalID)
cthis.startListening(10) //here,
callback && callback.apply(cthis, []) //and here
}
}, rate)
}
如果您想使用thisapply或call来实现em> 而不是 cthis
connect: function(to, rate, callback){
var cthis = this,
tempFunc = function(){
if(this.attemptConnect(to)){
clearInterval(connectIntervalID)
this.startListening(10)
callback && callback.apply(this, [])
}
}�
connectIntervalID = setInterval(function(){tempFunc.apply(cthis, [])}, rate)
}
然而,这似乎更糟糕......
I have a method that is a big setInterval statement, and it needs access to the this object of the object that owns the method from inside the interval. I implemented a simple closure, but it doesn't seem very elegant:
connect: function(to, rate, callback){
var cthis = this, //set cthis to this,
connectIntervalID = setInterval(function(){
if(cthis.attemptConnect(to)){ //reference it here,
clearInterval(connectIntervalID)
cthis.startListening(10) //here,
callback && callback.apply(cthis, []) //and here
}
}, rate)
}
You could also do it with apply or call, if you wanted to use this instead of cthis
connect: function(to, rate, callback){
var cthis = this,
tempFunc = function(){
if(this.attemptConnect(to)){
clearInterval(connectIntervalID)
this.startListening(10)
callback && callback.apply(this, [])
}
}�
connectIntervalID = setInterval(function(){tempFunc.apply(cthis, [])}, rate)
}
However, that seems even worse...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
.bind
会让它更好一点(在我看来,你可能同意也可能不同意):支持代码:
并且你的代码变成:
但我担心你不会得到很多更好的。
Using a
.bind
makes it a bit better (in my opinion, you may or may not agree):support code:
and your code becomes:
But I'm afraid you won't get a whole lot better.
您的第一个示例或多或少是执行此操作的标准方法。我唯一的建议是将你的变量命名为 cthis 以外的其他名称;使其描述被绑定的对象。
Javascript 1.8.5 添加了 Function.prototype.bind 以不同的方式解决这个问题,但这对大多数人来说并不是一个有用的解决方案。
Your first example is more-or-less the standard way to do this. My only suggestion would be to call your variable something other than cthis; make it descriptive of the object being bound.
Javascript 1.8.5 adds Function.prototype.bind to solve this problem in a different way, but that's not a useful solution for most people.
我会将
setInterval
函数分解为它自己的函数,并附加到与connect
相同的对象。这样,就可以清楚this
引用同一个对象:I'd break out the
setInterval
function into its own function, attached to the same object asconnect
. In this way, it will be clear thatthis
refers to the same object: