[英]JavaScript, anonymous vs direct function call
In the following snippet I am assigning anonymous function to onreadystatechange variable and everything works fine, but if I assign a named function to this variable it does not work. 在以下代码段中,我将匿名函数分配给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>
The above code works but the following does not. 上面的代码有效,但下面的无效。 The function
foo()
does not get called: 函数
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>
Why is that? 这是为什么?
The issue was resolved. 问题已解决。 var xmlHttp had to be global.
var xmlHttp必须是全局的。 Although I am not using xmlHttp in foo(), maybe it is needed internally by xmlHttp object!
尽管我没有在foo()中使用xmlHttp ,但是xmlHttp对象可能在内部需要它! Anybody knows why?
有人知道为什么吗? Anyway this issue is resolved for me.
无论如何,这个问题已为我解决。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.