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.
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.Meaning that your
InfoProp
property points to the initial value oflocalInformation
(the empty object), while within the function, you get the latest value oflocalInformation
.You have two options:
1) Extend the existing object instead of assigning the variable name to a new one:
You cann use jQuery's extend, ot the one from lodash, or any other implementation will do.
2) use a getter method