我有一个方法,它是一个大的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)
}
如果你想使用this而不是cthis,你也可以使用apply或call来实现。
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)
}
然而,这似乎更糟...