ivapopova

vehicleMixin_labs.js

Jan 5th, 2019
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2. // define driveMixin functionality in an object.
  3. // (the classical pattern suggest to use class, not object)
  4. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. const driveMixin = {
  6.     drive: function(){
  7.         console.log(`${this.model} is driving`);
  8.     },
  9.     stop: function(){
  10.         console.log(`${this.model} is stopped`);
  11.     },
  12.     jump: function(){
  13.         console.log(`${this.model} is jumping`);
  14.     }
  15. }
  16.  
  17. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  18. // the Vehicle base class
  19. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  20. function Vehicle(model){
  21.     this.model = model;
  22. }
  23. Vehicle.prototype.drive = driveMixin.drive;
  24. Vehicle.prototype.stop = driveMixin.stop;
  25.  
  26. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  27. // The Bike class - inherits from Vehicle
  28. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  29. function Bike(model){
  30.     Vehicle.call(this, model)
  31. }
  32. Bike.prototype = Object.create(Vehicle.prototype);
  33.  
  34. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  35. // The Car class - inherits from Vehicle
  36. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  37. function Car(model){
  38.     Vehicle.call(this, model)
  39. }
  40. Car.prototype = Object.create(Vehicle.prototype);
  41.  
  42.  
  43. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  44. // make some objects
  45. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  46. var ford = new Car("Ford");
  47. var harley = new Bike("Harley Davidson");
  48.  
  49. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  50. // use the driveMixin:
  51. // first 4 rows are commented, as we moved them to
  52. // Vehicle.prototype
  53. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  54. // ford.drive = driveMixin.drive;
  55. // ford.stop = driveMixin.stop;
  56. // harley.drive = driveMixin.drive;
  57. // harley.stop = driveMixin.stop;
  58. harley.jump = driveMixin.jump;
  59.  
  60.  
  61. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  62. // test the program
  63. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  64. ford.drive(); // 'The ford is driving'
  65. ford.stop();  // 'The ford is stopped'
  66.  
  67. harley.drive(); // 'Harley Davidson is driving'
  68. harley.stop();  // 'Harley Davidson is stopped'
  69.  
  70. harley.jump(); // 'Harley Davidson is stopped'
  71. ford.jump();   // Error!
Advertisement
Add Comment
Please, Sign In to add comment