How does the JavaScript variable change function work for variables inside a private IIFE namespace?
This is a piggyback from another question I asked. This was solved in the comments, so I am not looking for an answer to it. Here's where I would like to know about variable scopes:
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 due to asynchronous communication. So I get this,
JOHNNY.getStuff(5);
undefined
Again, I know why this is the case. This is not the part I am asking for (the asynchronous part).
My question is about this part:
I can get 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 the data to the var module
in the callback myCallBack
and I won't rely on the instant response, it is unreliable, etc.
What I am not getting is how the variable module
in the private namespace is updated after I have called this function and the link to JOHNNY has already been created.
In the console I have already made my call,
JOHNNY.getStuff (5);
did not return module
to IIFE? module
Does variable not require using prototype here to update all cases?
source to share
No one has answered this question yet
See similar questions:
or similar: