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
,color
andmodel
. Set default values of your own choice to them. -
Add a method named
drive(speed)
for theVehicle
object. This method should print"M of C color driving at S km/h!"
if the speed does not exceed max speed for the vehicle. ReplaceM
with vehicle's model,C
with it's color and S with thespeed
parameter passed to the function. If the givenspeed
exceeds the max speed of the vehicle, print a message"Sorry, M of C color can't go that fast"
. -
Create an object called
Car
. SetVehicle
as the prototype forCar
object. -
Add a new property to it:
numberOfSeats
, and a method:canSeat(numberOfPersons)
- it should return true, ifnumberOfPersons
people can sit in the car at the same time (legally, not how many can physically fit in there). -
Create an object called
redPorsche
. SetCar
as its prototype. Set the model, color and top speed accordingly. -
Call method
.drive(200)
for theredPorsche
object. Do you see the output in the console? -
Add a new property for the
Vehicle
object:numberOfWheels=4
. -
Print
redPorsche.numberOfWheels
in the console. What value do you get? You did not set number of wheels on the Porsche, how did theredPorsche
object get access to the property? -
Create a new object called
bike
. SetVehicle
as the prototype for it. - Set
bike.numberOfWheels = 2
. -
Now print
Vehicle.numberOfWheels
in the console. Then printredPorsche.numberOfWheels
andbike.numberOfWheels
in the console. Try to understand why you got these results! -
Inspect the
bike
object in the console (you can simply typebike
in 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.