Advertisement
SergioG_0823849

car inheritance

Apr 4th, 2024 (edited)
670
0
305 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Constructor function for base Vehicle
  2. function Vehicle(make, model) {
  3.   this.make = make;
  4.   this.model = model;
  5. }
  6.  
  7. // Method for starting the vehicle
  8. Vehicle.prototype.start = function() {
  9.   console.log(`Starting the ${this.make} ${this.model}`);
  10. };
  11.  
  12. // Constructor function for Car inheriting from Vehicle
  13. function Car(make, model, numDoors) {
  14.   // Call the parent constructor using call() or apply()
  15.   Vehicle.call(this, make, model);
  16.   this.numDoors = numDoors;
  17. }
  18.  
  19. // Inherit Vehicle prototype methods
  20. Car.prototype = Object.create(Vehicle.prototype);
  21. Car.prototype.constructor = Car;
  22.  
  23. // Override start method for Car
  24. Car.prototype.start = function() {
  25.   console.log(`Starting the ${this.make} ${this.model} with ${this.numDoors} doors`);
  26. };
  27.  
  28. // Test the classes
  29. const myVehicle = new Vehicle('Toyota', 'Camry');
  30. myVehicle.start(); // Output: Starting the Toyota Camry
  31.  
  32. const myCar = new Car('Honda', 'Civic', 4);
  33. myCar.start(); // Output: Starting the Honda Civic with 4 doors
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement