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

167
Views
¿Existe un atajo para asignar argumentos en un constructor a campos de clase? (Javascript)

En una clase como la siguiente:

 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; } }

Parece que hay muchas repeticiones al asignar todo al objeto de clase y me preguntaba si había alguna forma de hacerlo todo a la vez.

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

0

puedes asignarlo así.

 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, rx, ry, r.width, r.height, r.bgColor)

about 4 years ago · Juan Pablo Isaza Report

0

También puedes usar for...of loop así:

 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(bx, by, b.width, b.height, b.bgColor)

Thow La respuesta de Vinod Liyanage es más elegante y más corta.

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!