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.

Go back to exercise list.

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:

  1. Create an object called Vehicle. Add three properties for it: maxSpeed, color and model. Set default values of your own choice to them.
  2. Add a method named drive(speed) for the Vehicle 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. Replace M with vehicle's model, C with it's color and S with the speed parameter passed to the function. If the given speed exceeds the max speed of the vehicle, print a message "Sorry, M of C color can't go that fast".
  3. Create an object called Car. Set Vehicle as the prototype for Car object.
  4. Add a new property to it: numberOfSeats, and a method: canSeat(numberOfPersons) - it should return true, if numberOfPersons people can sit in the car at the same time (legally, not how many can physically fit in there).
  5. Create an object called redPorsche. Set Car as its prototype. Set the model, color and top speed accordingly.
  6. Call method .drive(200) for the redPorsche object. Do you see the output in the console?
  7. Add a new property for the Vehicle object: numberOfWheels=4.
  8. Print redPorsche.numberOfWheels in the console. What value do you get? You did not set number of wheels on the Porsche, how did the redPorsche object get access to the property?
  9. Create a new object called bike. Set Vehicle as the prototype for it.
  10. Set bike.numberOfWheels = 2.
  11. Now print Vehicle.numberOfWheels in the console. Then print redPorsche.numberOfWheels and bike.numberOfWheels in the console. Try to understand why you got these results!
  12. Inspect the bike object in the console (you can simply type bike in the console). What prototype does it have? What is the prototype of the prototype? Also, pay attention to numberOfWheels (this is one notable difference from Java!).

Solution

You can find a solution here.