Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
Why use constructor at all?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!