Javascript 访问私有(private)数组

标签 javascript html

我需要做到这一点,以便每次您单击一包口香糖的图片时,它都会根据单击的口香糖图片将总价格加在一起。它还必须计算点击图片的次数以显示购物车商品数量。我必须有一个私有(private)数组。但我似乎不知道如何调用它,这样我就可以获得被点击的口香糖的价格

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

最佳答案

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

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

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

关于Javascript 访问私有(private)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724307/

相关文章:

javascript - 使用javascript单击按钮更改元素的背景颜色样式

javascript - 在 typescript 中加载任何模块时如何传递参数?

javascript - 如何重置 Canvas 上下文的比例?

html - IE7幻影边框顶部

php - 使用 PHP 将 <a> 标记替换为 <b> 标记

html - 显示 : block. 垂直版本?

javascript - 模态窗口未占用完整的 100 宽度

javascript - 在可见时无法更改 Twitter Bootstrap 模式的选项

javascript - 如何在没有滚动的情况下使div的高度和宽度以特定的边距全屏显示

html - 可以使用 header 为 "Content-Disposition: attachment"的源作为 <img> 的 src 值吗?