我如何重构这个javascript以不使用全局?

时间:2015-09-29 16:06:43

标签: javascript

var groups;

function findGroups {
  getGroups().then(function (g) {
    groups = g;
  });
}

function foo() {
  var a = groups[0];  //or something along those lines.
  //access the properties of `g`
}

我想在整个页面的其他功能中访问g,因此我将其分配给全局变量。我一直认为全局变形很糟糕。我怎么能做到这一点?

由于

编辑:getGroups()是一个API调用。我不想多次打电话。

4 个答案:

答案 0 :(得分:1)

您可以在闭包中获取该函数,因此groups变量将是local:

(function(){
    var groups;

    function findGroups {
      getGroups().then(function (g) {
        groups = g;
      });
    }
})();

答案 1 :(得分:1)

如果您需要在多个页面中访问该变量,那么建立全局命名空间可能是一个很好的方法:

// file1.js (loaded first)
myApp = {}; // global namespace
(function() {
    var groups = {};

    myApp.findGroups = function() {
      return groups;
    };

    // init groups
    (function init() {
        getGroups().then(function (g) {
            groups = g;
        });
    }());
}());

// file2.js (loaded next)
myApp.findGroups(); // now myApp.groups is available

答案 2 :(得分:0)

或者你可以使用OOP风格:

var Group = {
    groups: null,
    findGroups: function() {
        getGroups().then(function (g) {
            Group.groups = g;
        });
    },
    fetchGroup: function(index){
        return Group.groups[index];
    }

};

Group.findGroups();
var group = Group.fetchGroup(index);

或者使用构造函数:

function Group(){
    this.groups = null;
    var self = this;
    this.findGroups = function() {
      getGroups().then(function (g) {
        self.groups = g;
      });
   };
};

var group = new Group();
group.findGroups();

答案 3 :(得分:0)

也许您只能拥有一个全局变量,然后就可以通过其公共接口访问数据。

示例:

var myLibrary;

(function (lib) {
    var groups;
    function findGroups() {
        getGroups().then(function (g) {
            groups = g;
        });
    }
    function getLocalGroups() {
        return groups;
    }

    //public interface
    lib.findGroups = findGroups;
    lib.getLocalGroups = getLocalGroups;
}(myLibrary));