简体   繁体   中英

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.

 <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:

 <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. Although I am not using xmlHttp in foo(), maybe it is needed internally by xmlHttp object! Anybody knows why? Anyway this issue is resolved for me. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM