Exercise 12.4
This is Exercise 12.4, lecture on prototype-based programming in Javascript, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.
Purpose
The purpose of the exercise is practice creating objects with prototypes.
Instructions
Create a new HTML document, and include a Javascript file called
app.js. Use that file to create the following:
-
Create an object called
Vehicle. Add three properties for it:maxSpeed,colorandmodel. Set default values of your own choice to them. -
Add a method named
drive(speed)for theVehicleobject. This method should print"M of C color driving at S km/h!"if the speed does not exceed max speed for the vehicle. ReplaceMwith vehicle's model,Cwith it's color and S with thespeedparameter passed to the function. If the givenspeedexceeds the max speed of the vehicle, print a message"Sorry, M of C color can't go that fast". -
Create an object called
Car. SetVehicleas the prototype forCarobject. -
Add a new property to it:
numberOfSeats, and a method:canSeat(numberOfPersons)- it should return true, ifnumberOfPersonspeople can sit in the car at the same time (legally, not how many can physically fit in there). -
Create an object called
redPorsche. SetCaras its prototype. Set the model, color and top speed accordingly. -
Call method
.drive(200)for theredPorscheobject. Do you see the output in the console? -
Add a new property for the
Vehicleobject:numberOfWheels=4. -
Print
redPorsche.numberOfWheelsin the console. What value do you get? You did not set number of wheels on the Porsche, how did theredPorscheobject get access to the property? -
Create a new object called
bike. SetVehicleas the prototype for it. - Set
bike.numberOfWheels = 2. -
Now print
Vehicle.numberOfWheelsin the console. Then printredPorsche.numberOfWheelsandbike.numberOfWheelsin the console. Try to understand why you got these results! -
Inspect the
bikeobject in the console (you can simply typebikein the console). What prototype does it have? What is the prototype of the prototype? Also, pay attention tonumberOfWheels(this is one notable difference from Java!).
Solution
You can find a solution here.