JavaScript object references behave strangely.

June 18, 2008 by Dave
 

I spent upwards of an hour trying to fix this bug that I introduced in some ‘AJAX’ code I was working on.

Basically, this was my original (vastly simplified and error checking removed) code:

function GetData(string url) {
 
req = new XHR();
 
req.open(url);
 
req.onreadystatechange = function() {
 
    if(req.readyState == 4 ) {
 
        document.getElementById('home').innerHTML += req.responseText;
 
        free_XHR(req);
 
    }
 
}
 
req.send(null);
 
 document.getElementById('home').innerHTML += "Waiting for data...";
 
}

This worked just fine, until I changed it to remove the multiple calls to document.getElementById and turned it into this:

function GetData(string url) {
 
req = new XHR();
home = document.getElementById('home');
req.open(url);
 
req.onreadystatechange = function() {
 
    if(req.readyState == 4 ) {
 
        home.innerHTML += req.responseText;
 
        free_XHR(req);
 
    }
 
}
 
req.send(null);
home.innerHTML += "Waiting for data...";
 
}

This had some really strange (or so I thought) effects. No errors were caused, but the home<div> was not properly written to.  It would add the text to that ‘home’ object.. a copy of the home div that didn’t exactly exist on the page. For all subsequent calls to the GetData routine, it would copy the home <div> and then effectively pipe the data nowhere.

The kicker?  req is still a correct reference object in the anonymous function that handles the readyState change., not a copy, but a reference to the req object created in the GetData call.  I’m still not exactly sure why this happens, perhaps it has something to do with the HTMLElement class not being passable in the same way that XMLHTTPRequest is.

Comments