See this problem, I was blindfolded, because at that time I do not clear this problem, thought for a while did not think out, and then to the Internet, a site found in foreign countries to say setinterval and settimeout after the scope of the function is global, that is, the inside of this point is the global object.
This problem can be troublesome, I often want to use this in the loop function to refer to the current object, maybe you think you can use closure, but the actual situation is not so simple, the object instance more, the closure is also out of order.
My wish is to let this in the loop function still points to the object in the current context, without the need to pass the parameter, no closure (in fact, this is also a closure, but the formal look more natural);
For example: (part of the code, the role is to send requests regularly)
Copy Code code as follows:
var sendrequest=function () {}
sendrequest.prototype={
.............................
.............................
Beginsend:function () {
To make this in the loop function point to this object, not to 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 data is sent to the background
if (this.data_wait_for_send.length!=0) {
for (Var i=0,j=this.data_wait_for_send.length;i<j;i++) {
post_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);
},
......................
......................
}
So, in the Sendarequest () function, we can normally use this to refer to the current object, using the variables and methods of the current object, so it's not convenient?