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?
Therefore, only two instances of class A are created. Save this answer. Show activity on this post. Two.
Note: A class cannot have more than one constructor() method. This will throw a SyntaxError . You can use the super() method to call the constructor of a parent class (see "More Examples" below).
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
constructor. The constructor property returns a reference to the Object constructor function that created the instance object.
Yes, there is a (minor) reason you shouldn't use a constructor: the instance will hold a reference to the constructor function via instance.[[Prototype]].constructor
, and thus it won't be garbage collected. It will waste memory uselessly because you won't instantiate it again.
var cart = new function(){ /* ... */ };
console.log(cart.constructor); // Won't be garbage-collected
If you prefer a function approach you can still do something like the following. This way you can also have private variables.
var cart = function() {
// You can add private variables here
this.items = {};
this.increaseItemQty = function(partNumber) {
if(this.items[partNumber]) {
this.items[partNumber].qty += 1;
} else {
this.items[partNumber] = {
qty : 1
};
}
};
return this;
}.call({});
cart.increaseItemQty(0);
console.log(cart.items);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With