Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda