Game Development Reference
In-Depth Information
The nice thing is that you can now create lots of dogs that can bark, but you only have to define the
bark
method once:
var max = new Dog();
var zoe = new Dog();
var buster = new Dog();
max.bark();
zoe.bark();
buster.bark();
Of course, the goal of this topic is not to show you how to become a dog breeder, but how to create
games. And for games, the prototype concept is very powerful. It allows you to
separate the actual
objects that are used in your game from how they should be constructed
.
As an exercise, let's apply the prototype principle to creating a
ball
object. In order to do this,
you need to define a function. Let's call this function
Ball
, and let's add the
initialize
method to
the prototype:
function Ball() {
}
Ball.prototype.initialize = function() {
// ball object initialization here
};
In the
initialize
method, you have to define variables that are part of each
ball
object you create.
The problem is, you didn't make an object yet—you only have a function and a prototype that
contains an
initialize
method. So in the body of the
initialize
method, how do you refer to
the object this method belongs to? In JavaScript, the
this
keyword is used for that purpose. In a
method,
this
always refers to the object the method belongs to. Using that keyword, you can fill in
the body of the
initialize
method:
Ball.prototype.initialize = function() {
this.position = { x : 0, y : 0 };
this.velocity = { x : 0, y : 0 };
this.origin = { x : 0, y : 0 };
this.currentColor = sprites.ball_red;
this.shooting = false;
};
You can now create as many balls as you want and initialize them:
var ball = new Ball();
var anotherBall = new Ball();
ball.initialize();
anotherBall.initialize();
Each time you create a new ball, any methods in the prototype are added to the object. When the
initialize
method is called on the
ball
object,
this
refers to
ball
. When it's called on
anotherBall
,
this
refers to
anotherBall
.
Search WWH ::
Custom Search