Home > Web Front-end > JS Tutorial > JavaScript makes this in the function parameters in setInteval point to a specific object_javascript tips

JavaScript makes this in the function parameters in setInteval point to a specific object_javascript tips

WBOY
Release: 2016-05-16 18:35:41
Original
1048 people have browsed it

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)

Copy code The code is as follows :

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?
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template