This is a piggyback off another question I asked. It was solved in the comments, so I'm not looking for answer to it. I wanted to know about variable scoping here:
var JOHNNY = (function()
{
var module = {};
function getData(id, callback){
var xhr = new XMLHttpRequest();
var url = "http://someurl/api/5";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status == 200)) {
callback(xhr.response);
}
};
xhr.open("GET", url, true);
xhr.responseType = 'json';
xhr.send(null);
}
function myCallBack(data){
return data; //console.log works;
}
module.getStuff=function(id){
return getData(5, myCallBack); //just hardcoded id here
}
return module;
})();
I know why this doesn't work because of the async communication. So, I get this,
JOHNNY.getStuff(5);
undefined
Again, I know why that is. That is not the part I'm asking about (the async part).
My question has to do with this part:
I can get the data if I do this,
function myCallBack(data){
module.test = data;
}
and then,
JOHNNY.test;
//has the answer, 5,; this assumes the callback has been called for the questions sake.
The callback assigns data to the var module
in the callback, myCallBack
, and I wouldn't rely on an instant answer, this is unreliable, and so forth.
What I don't get is how the module
variable in the private namespace is updated after I have called the function and a reference to JOHNNY has already been created.
In the console I had already done my call,
JOHNNY.getStuff(5);
hasn't module
already been returned in the IIFE? The variable module
doesn't require prototype to be used here to update all occurrence?