It is said that Alibaba's campus recruitment this year has a question that tests a knowledge point, and that is the this pointer in the parameter function of setInterval.
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. When 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 closure (in fact, this is also a closure, but it looks more natural in form);
For example: (Part of the code is used to send requests regularly)
1 var sendRequest=function(){}
2 sendRequest.prototype={
3........................................
4 .............................
5 beginSend:function(){
6 //Make this in the loop function point to this object instead of the global object
7 this.loop_send=setInterval((function(param){
8 return function(){param.sendARequest();}
9 })(this),this.options.interval);
10},
11 sendARequest:function(){
12 this.num++;
13 this.checkLimit();
14 var callback = {
15 success: this.handleSuccess,
16 failure: this.handleFail,
17 argument: {
18 handle: this,
19 timeout:500
20}
twenty one }
22 var post_data="...."
23 //If the data to be sent is not empty, a piece of data will be taken out and sent to the background
24 if(this.data_wait_for_send.length!=0){
25 for(var i=0,j=this.data_wait_for_send.length;i<j;i++){
26 post_data+="&content[]="+this.data_wait_for_send[i];
27}
28 this.data_wait_for_send=[]
29 }
30 //debug(post_data)
31 var que = Connect.asyncRequest('POST', this.options.getUrl, callback,post_data);
32},
33............................
34............................
35}
36
-