The problem with xmlhttp.onreadystatechange=function

function myCallBack(xmlhttp) {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        console.log(xmlhttp.responseText);
    }
}
function start() {
    var xmlhttp = new XMLHttpRequest();
    var contentDiv = document.getElementById("Content");
    xmlhttp.open("POST", "Demo", true);
    xmlhttp.onreadystatechange=function() {
      myCallBack(xmlhttp);
    };
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
    xmlhttp.send("FirstName=Nat&LastName=Dunn");
}

Why can"t the above code be written as

function myCallBack(xmlhttp) {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        console.log(xmlhttp.responseText);
    }
}
function start() {
    var xmlhttp = new XMLHttpRequest();
    var contentDiv = document.getElementById("Content");
    xmlhttp.open("POST", "Demo", true);
    xmlhttp.onreadystatechange=myCallBack(xmlhttp);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
    xmlhttp.send("FirstName=Nat&LastName=Dunn");
}

the difference between the two pieces of code

xmlhttp.onreadystatechange=myCallBack(xmlhttp);  

xmlhttp.onreadystatechange=function() {
    myCallBack(xmlhttp);
};     

Dec.10,2021

xmlhttp.onreadystatechange=myCallBack

xmlhttp.onreadystatechange=myCallBack(xmlhttp);

assigns myCallBack (xmlhttp) the execution result of this function to xmlhttp.onreadystatechange . In fact, myCallBack (xmlhttp) returns undefined . So the above code is equivalent to

xmlhttp.onreadystatechange=undefined

and

xmlhttp.onreadystatechange=function() {
    myCallBack(xmlhttp);
};  

this assigns a function to xmlhttp.onreadystatechange .

Menu