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

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

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 Relatório

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