Exercise 12.3

This is Exercise 12.3, lecture on objects and prototypes 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 different ways of creating objects in Javascript.

Instructions

Create a new HTML document, and include a Javascript file called app.js. In that file, create objects using four possible ways:

  1. object literals
  2. constructor functions
  3. classes
  4. Object.create() method

See the four methods explained in lecture slides. Note: you must name the different objects differently (for example, person1, person2, person3, and person4)! Create the following objects:

  1. Four Person objects which have a firstname and a lastname.
  2. Two GameObject objects (player and enemy). Note: if you are ambitious, you can create these objects using all the four ways mentioned above. But you can also choose just one of the ways. For example, create both GameObject instances using a class. Imagine that these are objects placed in a 2D game. Each GameObject must have the following properties:
    • x_position: number
    • y_position: number
    • name: string
    • life: number
    Each GameObject must have the following methods (functions):
    • A constructor which allows to set the (x, y) position, name and life.
    • decreaseLife(delta) - decrease the life of the object by delta. The life does not go lower than zero.
    • move(deltaX, deltaY) - change the (x,y) position of the object by deltaX and deltaY.
    • isAlive() - returns true when the value of the life property is positive.

Solution

You can find a solution here.