Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda