I came across the thought that I honestly never had to use class nor constructor all this time and started to wonder if there are cases where I should use them? For example, below codes are basically same except one uses constructor and one doesn't.
Using constructor:
function Food(foodName, foodPrice) {
Currencies.call(this, foodPrice);
this.category = 'food';
this.name = foodName;
}
function Currencies(usd) {
this.usd = usd;
this.won = +usd * 1000;
}
const pizza = new Food('pizza', 30); // { usd: 30, won: 30000, category: 'food', name: 'pizza' }
const burger = new Food('burger', 10); // { usd: 30, won: 30000, category: 'food', name: 'pizza' }
Not using constructor
function food(foodName, foodPrice) {
return { name: foodName, category: 'food', ...(currencies(foodPrice)) }
}
function currencies(usd) {
return { usd, won: usd * 1000 }
}
const pizza = food('pizza', 30); // { usd: 30, won: 30000, category: 'food', name: 'pizza' }
const burger = food('burger', 10); // { usd: 30, won: 30000, category: 'food', name: 'pizza' }
To me, not using constructor seems bit simpler so I would avoid using it AMAP. What do you prefer and why? And when exactly do you decide to use constructor instead of "regular" function?
A constructor enables you to write methods to the object itself, which you can not do without a constructor. In addition to that, you can provide custom initialization that must be done before any other methods can be called on an instantiated object. You can also inherit from one class to another using extends operator. This saves you time from re-writing the same thing over and over again and provides better and easier control over your objects.
Refer to the following link for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor