[英]Passing arguments to anonymous Javascript functions
考虑下面的代码:
this.usedIds = 0;
this.SendData = function(data)
{
var id = this.usedIds;
this.usedIds++;
this.xmlHttpThing.open("POST", "/Upload.aspx", true);
this.xmlHttpThing.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var currentObject = this;
this.xmlHttpThing.onreadystatechange = function() { currentObject.UploadComplete(id) };
this.xmlHttpThing.send(data);
};
this.UploadComplete = function(id)
{
if (this.xmlHttpThing.readyState == 4)
{
//First time id is 0
//Second time id is 0 <<<--------- Why??
//Third time id is 1
//Fourth time id is 2
//Fifth time id is 3 ....
this.SendData("blabla");
}
};
为什么我传递给匿名函数的 id 在第一次调用后被一次调用延迟?
在 Firefox 中似乎只有这种方式,在 IE 中, UploadComplete
以正确的顺序接收 ID。
在第二个循环中,我可以在 send(data) 行停止调试器并确认 id 实际上为 1,但是当我到达UploadComplete
时,该参数中的值为 0 :(
编辑:找到解决方案:
在 FireBug 中禁用控制台日志记录。
我过去也遇到过同样的问题。 我不记得到底是什么导致了它,但我通过将增量移动到响应处理程序来修复它。
this.UploadComplete = function(id)
{
if (this.xmlHttpThing.readyState == 4)
{
this.usedIDs++;
this.SendData("blabla");
}
};
编辑:仔细想想,我的情况可能与你的不同。 为什么在分配id
时不增加this.usedIDs
?
var id = this.usedIDs++;
在 Firebug 中禁用控制台日志解决了这个问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.