Return a variable as a property in an IIFE

自作多情 提交于 2019-12-10 15:54:35

问题


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:


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 },
  ....
} 


来源:https://stackoverflow.com/questions/41542683/return-a-variable-as-a-property-in-an-iife

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!