Return a variable as a property in an IIFE

925 views Asked by At

I am trying to return a variable set after the initialization of an IIFE as a property. The issue is if I bind the variable directly, I get an empty object. If I bind it through a function, I get my desired result.

var Application = (function(){

    var localInformation = {};

    function init(){
        localInformation = _demoApiCall();
    }

    function _demoApiCall(){
        // Pretend this method isn't here, and returns a complex object
        return {
            name: "Demo"
        }
    }

    function doWork(){
        // localInformation is properly structured here if called
    }

    return {
        Init: init,
        DoWork: doWork,
        InfoProp: localInformation, // returns {}
        InfoMethod: function(){
            return localInformation; // returns {name:"demo"}
        }
    }

})();

Application.Init();

console.log(Application.InfoProp);
console.log(Application.InfoMethod());

After initially calling Application.Init() on document ready, the example will only work if I call var inf = Application.InfoMethod(), however it would be much cleaner if I could call var info = Application.InfoProp.

I've tried to read up on JS Closures, but haven't gotten any information into why there would be no proper reference to the private variable.

1

There are 1 answers

4
lordvlad On BEST ANSWER

I guess you meant to write localInformation in your returned object.

The problem is that you are re-assigning the localInformation variable name to a new object.

localInformation = _demoAPICall()

Meaning that your InfoProp property points to the initial value of localInformation (the empty object), while within the function, you get the latest value of localInformation.

You have two options:

1) Extend the existing object instead of assigning the variable name to a new one:

extend(localInformation, _demoApiCall())

You cann use jQuery's extend, ot the one from lodash, or any other implementation will do.

2) use a getter method

return {
  Init: Init,
  get InfoProp () { return information },
  ....
}