[英]JavaScript, anonymous vs direct function call
在以下代码段中,我将匿名函数分配给onreadystatechange变量,并且一切正常,但是如果我给该变量分配一个命名函数,它将无法正常工作。
<script language="Javascript">
function postRequest(strURL)
{
var xmlHttp;
if (window.XMLHttpRequest) // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject) // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
alert("you are in anonymous");
}
xmlHttp.send(strURL);
}
</script>
上面的代码有效,但下面的无效。 函数foo()
不会被调用:
<script language="Javascript">
function foo()
{
alert("you are in foo");
}
/*----------------------------------------------*/
function postRequest(strURL)
{
var xmlHttp;
if (window.XMLHttpRequest) // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject) // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = foo;
xmlHttp.send(strURL);
}
</script>
这是为什么?
问题已解决。 var xmlHttp必须是全局的。 尽管我没有在foo()中使用xmlHttp ,但是xmlHttp对象可能在内部需要它! 有人知道为什么吗? 无论如何,这个问题已为我解决。 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.