var mapFile = new XMLHttpRequest();
mapFile.open("GET", "http://localhost:8000/res/map01.txt", true);
mapFile.onreadystatechange = function() {
if (mapFile.readyState === 4) {
if (mapFile.status === 200) {
this.lines = mapFile.responseText.split("\n");
}
}
}
this.lines = mapFile.onreadystatechange.lines;
mapFile.send(null);
I have that code and I’m trying to save this.lines inside mapFile.onreadstatechange to later save as this.lines on the outer scope. However, mapFile.onreadystatachange.lines is undefined and I can’t save the variable for later use. I even tried using element.innerHTML which is a dirty hack for this but it also didn’t work.
There are three primary issues here:
The
thiswithinonreadystatechangeis not the same as thethisoutside of the function, becausethiswithin a function is determined by how the function is called. More on my blog: Mythical methods | You must rememberthisXHR calls are asynchronous (by default), so your callback won’t have been called yet when you’re trying to use
this.linesjust above thesendcall. (Even with a synchronous request, since that line is beforesend, it still wouldn’t be set.)mapFile.onreadystatechange.lineslooks for a property calledlineson the function object referenced bymapFile.onreadystatechange. It has absolutely nothing to do with any variables defined within that function.Here’s an update addressing the main items: