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

165
Vistas
Is there a shortcut for assigning arguments in a constructor to class fields? (Javascript)

In a class like the following:

class Rect {
  constructor({ x = 0, y = 0, width = 0, height = 0, bgColor = "#000000" } = {}) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.bgColor = bgColor;
  }
}

It seems like there's a lot of repetition when assigning everything to the class object and I was wondering if there was some way to do it all at once.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

you can assign it like this.

class Rect {
  constructor({ x = 0, y = 0, width = 0, height = 0, bgColor = "#000000" } = {}) {
   Object.assign(this, {x, y, width, height, bgColor})
  }
}

const r = new Rect()
console.log(r, r.x, r.y, r.width, r.height, r.bgColor)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can also use for...of loop like so:

class Rect {
   constructor(param = { x: 0, y: 0, width: 0, height: 0, bgColor: "#000000" }) {
      for (const [key, value] of Object.entries(param)) {
         this[key] = value
      }
   }
};

const b = new Rect();
console.log(b.x, b.y, b.width, b.height, b.bgColor)

Thow Vinod Liyanage's answer is more elegant and is shorter.

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