When I saw this question, I was confused because I didn't clear up the problem at that time. I thought about it for a long time and couldn't figure it out. Then I checked online and found on a foreign website that the scope of the functions after setInterval and setTimeout is global. , that is, this inside points to the global object.
This problem is troublesome. I often use this to refer to the current object in the loop function. Maybe you think of using closures, but the actual situation is not that simple. , after there are too many object instances, closures become messy.
My wish is to make this in the loop function still point to the object of the current context, without passing parameters or closures (in fact, this is also a closure, but in form It just looks more natural);
For example: (Part of the code, the function is to send requests regularly)
var sendRequest=function(){}
sendRequest.prototype={
............. ...........
.............................
beginSend:function() {
//Make this in the loop function point to this object instead of the global object
this.loop_send=setInterval((function(param){
return function(){param.sendARequest();}
})(this),this.options.interval);
},
sendARequest:function(){
this.num ;
this.checkLimit();
var callback = {
success: this.handleSuccess,
failure: this.handleFail,
argument: {
handle: this,
timeout:500
}
}
var post_data="...."
//If the data to be sent is not empty, a piece of data will be taken out and sent to the background
if(this.data_wait_for_send.length!=0){
for(var i=0,j=this.data_wait_for_send.length;ipost_data ="&content[]=" this.data_wait_for_send[i];
}
this.data_wait_for_send =[]
}
// debug(post_data)
var que = Connect.asyncRequest('POST', this.options.getUrl, callback,post_data);
},
. ..................
........................
}
In this way, in the sendARequest() function, we can use this to refer to the current object normally and use the variables and methods of the current object. Isn’t this very convenient?