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

325
Vistas
How to define constructor function with destructuring in Javascript

I want to build a Vehicle class to create objects based on it. And I want to pass an object to the constructor function as a parameter such that const vehicle = new Vehicle({vehicleType: 'car', name: 'car1', range: 500})

I have built it like below but how can I destructure the constructor parameter in order to avoid repeating 'options.' word?

class Vehicle {
  constructor(options = { vehicleType: 'car', name: '', range: '', seats: '' }) {
    this.vehicleType = options.vehicleType
    this.name = options.name
    this.range = options.range
    this.seats = options.seats
  }

  getRangeToSeatsRatio() {
    return this.range / this.seats
  }

  multiplySeatsBy(count) {
    this.seats *= count
    return this
  }

  getSeatCount() {
    return this.seats
  }

  get rangeToSeatsRatio() {
    return this.range / this.seats
  }

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

0

you can do it this way:

class Vehicle {
  constructor(options) {
    const { vehicleType = 'car', name = '', range = '', seats = '' } = options;
    this.vehicleType = vehicleType
    this.name = name
    this.range = range
    this.seats = seats
  }

  getRangeToSeatsRatio() {
    return this.range / this.seats
  }

  multiplySeatsBy(count) {
    this.seats *= count
    return this
  }

  getSeatCount() {
    return this.seats
  }

  get rangeToSeatsRatio() {
    return this.range / this.seats
  }

  
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do it like this:

class Vehicle {
  vehicleType = 'car';
  name = '';
  range = '';
  seats = '';

  constructor(options) {
    Object.assign(this, options);
  }

  getRangeToSeatsRatio() {
    return this.range / this.seats
  }

  multiplySeatsBy(count) {
    this.seats *= count
    return this
  }

  getSeatCount() {
    return this.seats
  }

  get rangeToSeatsRatio() {
    return this.range / this.seats
  }

}
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