簡體   English   中英

我將如何重構此JavaScript以不使用全局變量?

[英]How would I refactor this javascript to not use a global?

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調用。 我不想多次調用它。

您可以在閉包中獲取該函數,因此groups變量將是局部的:

(function(){
    var groups;

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

如果您需要跨多個頁面訪問該變量,則建立全局名稱空間可能是一個好方法:

// 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

或者您可以使用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();

也許您只有一個全局變量,然后可以通過其公共接口訪問數據。

例:

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM