您必须为每个对象调用一个函数,以便为每个对象生成不同的变量,例如:
var basketModule = function() { var basket = []; return { addItem: function(values) { basket.push(values); }, getItemCount: function() { return basket.length; } }; }; var carBasket = basketModule(), foodBasket = basketModule(); carBasket.addItem('Audi'); foodBasket.addItem('Ham'); foodBasket.getItemCount(); // 1
但是,为了重用所有实例的方法,最好使用构造函数:
var BasketModule = function() { this.basket = []; }; BasketModule.prototype.addItem = function(values) { this.basket.push(values); }; BasketModule.prototype.getItemCount = function() { return this.basket.length; }; var carBasket = new BasketModule(), foodBasket = new BasketModule(); carBasket.addItem('Audi'); foodBasket.addItem('Ham'); foodBasket.getItemCount(); // 1