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

326
Views
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 answers
Answer question

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 Report

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