I've been traveling deeper into the JS world and came across 3 different ways I could develop the frontend cart of a website:
Constructor with Prototype Functions
var cart = function(){
this.items = {}
}
cart.prototype.increaseItemQty = function(partNumber){
if(this.items[partNumber]){
this.items[partNumber].qty += 1;
} else {
this.items[partNumber] = {
qty : 1
};
}
}
cart = new cart();
Methods Within the Constructor
var cart2 = function(){
this.items = {};
this.increaseItemQty = function (partNumber) {
if(this.items[partNumber]){
this.items[partNumber].qty += 1;
} else {
this.items[partNumber] = {
qty : 1
};
}
}
}
cart2 = new cart2();
Object Methods
var cart3 = {
items : {},
increaseItemQty : function(partNumber){
if(this.items[partNumber]){
this.items[partNumber].qty += 1;
} else {
this.items[partNumber] = {
qty : 1
};
}
}
};
If I know that there will only be one instance of the cart, then should I just use the Object Method
method? Is there any reason why I should still use a constructor?