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?