当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript让setInteval里的函数参数中的this指向特定的对象

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript让setInteval里的函数参数中的this指向特定的对象


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-02-27   浏览: 337 ::
收藏到网摘: n/a

话说阿里巴巴今年的校园招聘有一道题目考了一个知识点,那就是setInterval的参数函数里的this指向. 看到这个题,我蒙了,因为那时候我不清除这个问题,想了半天没想出来,后来到网上一查,在国外的某网站查到说setInterval和setTimeout之后的函数的作用域是全局的,也就是里面的this指向的是全局对象.
这个问题可麻烦了,我经常要在循环函数里用this来引用当前对象,也许你想到可以用闭包,不过实际情况并非如此简单,对象实例多了之后,闭包也乱套了.
我的愿望就是让循环函数里的this仍然指向当前上下文的对象,无需传参数,无需闭包(其实这也是闭包,只是形式上看着比较自然而已);
例如:(一部分代码,作用是定时发送请求)
复制代码 代码如下:

var sendRequest=function(){}
sendRequest.prototype={
.............................
.............................
beginSend:function(){
//使循环函数里的this指向本对象,而不是全局对象
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(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);
},
......................
......................
}

如此,在sendARequest()函数里,我们可以正常使用this来引用当前对象,使用当前对象的变量和方法,这样岂不是很方便? "