Game Development Reference
In-Depth Information
Suppose you want to be able to shoot three balls at the same time in the Painter game. If you did
this the way you created objects until now, you would create two variables,
ball2
and
ball3
, and
copy the code you used for the
ball
object twice. This isn't a very nice solution, for several reasons.
For one, copying code means you have to deal with version-management problems. For example,
what if you find a bug in the
update
method code? You have to make sure you copy the improved
code to the other
ball
objects. If you forget one copy, the bug is still there when you thought you
solved it. Another problem is that this approach simply doesn't scale up very well. What happens
if you want to extend the game such that the player can shoot 20 balls at the same time? Do you
copy the code 20 times? Also note that the bigger your JavaScript files become, the longer it takes
for the browser to download and interpret them. So, if you don't want your players waiting too long
for scripts to load, it's better to avoid copying code. Finally, duplicated code looks ugly, clutters up
your source code files, and makes it hard to find other sections of the code that you need, leading to
excessive scrolling and a general reduction of your coding efficiency.
Fortunately, there is a very nice solution to this problem. It's a JavaScript programming construct
called
prototypes
. Prototypes allow you to define a sort of blueprint for an object, including the
variables and methods it contains. Once this prototype is defined, you can create objects using
that prototype with a single line of code! You have already used something like this. Look at this
line of code:
var image = new Image();
Here, you create an
image
object that uses the
Image
prototype to construct itself.
Defining a prototype is easy. Have a look at this example:
function Dog() {
}
Dog.prototype.bark = function () {
console.log("woof!");
};
This creates a function called
Dog
. When this function is called in combination with the
new
keyword,
an object is created. Each function in JavaScript has a
prototype
that contains information about
what objects should look like that are created by calling the function together with the
new
keyword.
This example defines a method called
bark
that is part of the prototype of
Dog
. The
prototype
word
isn't just there for aesthetics. With it, you indicate that you're adding things to the prototype of
Dog
.
Whenever you create a
Dog
object, only the things that are part of its prototype are part of the object.
Here is how you create a new
Dog
object:
var lucy = new Dog();
Because
lucy
is created according to the prototype in the
Dog
function, the
lucy
object contains a
method called
bark
:
lucy.bark(); // outputs "woof!" to the console
Search WWH ::
Custom Search