Home > Mobile >  How to define constructor function with destructuring in Javascript
How to define constructor function with destructuring in Javascript

Time:03-15

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
  }

  
}

CodePudding user response:

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
  }

  
}

CodePudding user response:

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
  }

}
  • Related