JS Classes

Basic class creation in JavaScript

by Gustavo

JavaScript

/**
1) Design a class for vehicle which takes brand and model during construction of object and has a price property. /1/
2) Design a class for bus, which is vehicle, and can have  seats property
*/

class Vehicle {

	constructor(brand, model) {
  	if (!brand || !model) {
    	throw new Error('Brand and model are required.');
    }
  	this.brand = brand;
    this.model = model;
    this.price = null;
  }
  
  getBrand() {
  	return this.brand;
  }
  
  getModel() {
  	return this.model;
  }
  
  setPrice(price) {
  	this.price = price;
  }
  
  getPrice() {
  	return this.price;
  }
  
}

class Bus extends Vehicle {
 
  setSeats(seats) {
  	this.seats = seats;
  }
  
  getSeats() {
  	return this.seats;
  }
    
}

const vehicle = new Vehicle('Toyota', 'Corolla');
vehicle.setPrice(10000);

const bus = new Bus('Mercedez Benz', '1114');
bus.setSeats(20);

console.log(vehicle.getBrand(), vehicle.getModel(), vehicle.getPrice());
console.log(bus.getBrand(), bus.getModel(), bus.getPrice(), bus.getSeats());