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.
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:
- object literals
- constructor functions
- classes
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:
-
Four
Personobjects which have a firstname and a lastname. -
Two
GameObjectobjects (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 bothGameObjectinstances using a class. Imagine that these are objects placed in a 2D game. EachGameObjectmust have the following properties:x_position: numbery_position: numbername: stringlife: number
GameObjectmust 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 bydelta. The life does not go lower than zero. -
move(deltaX, deltaY)- change the (x,y) position of the object bydeltaXanddeltaY. -
isAlive()- returns true when the value of thelifeproperty is positive.
Solution
You can find a solution here.