Javascript访问私有数组

时间:2015-11-15 19:56:47

标签: javascript html

我需要这样做,所以每当你点击一包口香糖的时候,它会根据点击的口香糖img一起增加总价。它还必须计算imgs点击显示购物车项目金额的时间。我必须有一个私人阵列。但我似乎无法弄清楚如何调用它,所以我可以得到被点击的口香糖的价格

var addPrice = function(gum) {

    total = 0;
    if (gum == extra) {
        total += brands.price[0];
    }
    if (gum == twoMint) {
        total += brands.price[1];
    }
    if (gum == trident) {
        total += brands.price[2];
    }
    if (gum == bubble) {
        total += brands.price[3];
    }
    document.getElementById("totalAmount").innerHTML = total;
};

var clear = function() {
};

var createArray = function() {

    var gumArray = function() {

        var brands = [{
            brand: "extra",
            price: 1.50
        }, {
            brand: "twoMint",
            price: 0.25
        }, {
            brand: "trident",
            price: 2.50
        }, {
            brand: "bubble",
            price: 0.10
        }]
    };
};

document.getElementById("extra").addEventListener("click", function() {
    addPrice("extra"); -
    console.log("gum clicked");
});

document.getElementById("twoMint").addEventListener("click", function() {
    addPrice("twoMint");
    console.log("gum clicked");
});

document.getElementById("trident").addEventListener("click", function() {
    addPrice("trident");
    console.log("gum clicked");
});

document.getElementById("bubble").addEventListener("click", function() {
    addPrice("bubble");
    console.log("gum clicked");
};

2 个答案:

答案 0 :(得分:2)

如果您打算为此代码创建一个模块,让我向您展示一个模块的示例,很难说只有一件事可以将您的代码转换为模块。

您需要一个函数来返回一个对象,该对象从创建的闭包中访问变量。除非您将其作为模块的一部分公开,否则这些变量对外部不可见。

var cart = (function() {
  // These vars are private, not directly accessible from the outside
  var total = 0;
  // Map for faster access
  var brands = {extra: 1.50, twoMint: 0.25, trident: 2.50, bubble: 0.10};
  // Private function
  function updateUI() {
      document.getElementById("totalAmount").innerHTML = total;
  }

  // The exported module
  return {
      addPrice: function(gum) {
          total += brands[gum];
          updateUI();
      },
      // The outside can get the value of total, but they can't change it directly
      getTotal: function() {
          return total;
      },

      clear: function() {
          total = 0;
          updateUI();
      }

  };
})();

["extra", "twoMint", "trident", "bubble"].forEach(function(id){
  document.getElementById(id).addEventListener("click", function() {
   cart.addPrice(id);
  });
});

答案 1 :(得分:-1)

brands数组是内部范围内的局部变量。没有办法从关闭之外访问品牌阵列,至少你不会做类似的事情:

var brandsArray = createArray()();

然后,当您需要从addPrice访问brands数组时,您可以执行以下操作:

public string GetStoreNameById(int id){
   var httpContext = HttpContext.Current;
   //if no httpContext, just return from the db
   //rare but could throw a NullRefEx
   if(httpContext == null) return db.GetStore(id).Name;
   //build your key
   var key = string.format("Store-{0}", id);
   //if we get a cache miss, add the item from the db
   if(httpContext.Items[key] == null){
      var storeName = db.GetStore(id).Name;
      //note: there are overloads of this function for expiry times, etc.
      httpContext.Items.Add(key, storeName);
   }
   //return the value
   return httpContext.Items[key];
}

然而,走向这个方向并不是一个好习惯。有更好的方式来提供你想要的东西。例如,使用类似Juan Mendes答案的模块模式。