JavaScript/OOP-classes/Exercises
Appearance
Topic: OOP - 2
1. Create a class 'Car' with (minimum) two properties.
Click to see solution
"use strict";classCar{constructor(brand,model){this.brand=brand;this.model=model;}show(){return"My car is a "+this.brand+" "+this.model;}}constmyCityCar=newCar("Fiat","Cinquecento");constmySportsCar=newCar("Maserati","MC20");alert(myCityCar.show());alert(mySportsCar.show());
2. Create a class 'Truck' that is a sub-class of the above 'Car' class. It has an additional property 'maxLoad'.
Click to see solution
"use strict";classCar{// same as aboveconstructor(brand,model){this.brand=brand;this.model=model;}show(){return"My car is a "+this.brand+" "+this.model;}}classTruckextendsCar{constructor(brand,model,maxLoad){super(brand,model);this.maxLoad=maxLoad;}show(){return"My truck is a "+this.brand+" "+this.model+". It transports up to "+this.maxLoad;}}constmyTruck=newTruck("Caterpillar","D350D","25 tonne");alert(myTruck.show());