Jon Jon - 4 years ago 98
Javascript Question

Variables Pointing To The Same Function

I have created a new variable,

carBasket
and
foodBasket
, and set them equal to the
basketModule()
function. They however are pointed to the same function when I want each of these two variables pointed to their own function. I am wondering what should I be doing to achieve this?

var basketModule = (function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
}());

carBasket = basketModule;
carBasket.addItem('Audi');

foodBasket = basketModule;
foodBasket.addItem('Ham');

foodBasket.getItemCount(); //outputs 2 instead of 1

Answer Source

You must call a function for each object in order to generate different variables for each one, e.g:

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

However, in order to reuse the methods for all instances, better use a constructor:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download