3

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?

Community
  • 1
  • 1
johnny
  • 19,272
  • 52
  • 157
  • 259
  • 1
    module is just a referenced object, this means any assignment you'll do to it, will mutate the object. – elad.chen Mar 29 '17 at 14:00
  • "a reference to JOHNNY has already been created it." - you lost me here. Please, straighten out your verbs, nouns and pronouns. – Igor Mar 29 '17 at 14:07
  • This question might help: http://stackoverflow.com/questions/7389069/console-log-object-at-current-state – Dan Mar 29 '17 at 14:08
  • Since you use IIFE, `JOHNNY` is eventually assigned to `module` (which is returned by IIFE), i.e.: `JOHNNY = module`. – hindmost Mar 29 '17 at 14:12
  • @Igor I removed the word "it." – johnny Mar 29 '17 at 14:12

0 Answers0