Game Development Reference
In-Depth Information
Read-Only Properties
Following the prototype-based programming paradigm, you want to be able to add properties to
classes. JavaScript has a handy method called defineProperty that allows you to do this. This
method is part of an object, elusively called Object . Object has a couple of other useful methods as
well, as you learn later. The defineProperty method expects three parameters:
The prototype to which the property should be added
(for example, Cannon.prototype )
The name of the property (for example,
color )
An object containing at most two variables:
get and set
The get and set variables each should point to a function that should be executed when the
property is read or written. However, it's possible to define only a get or a set part. This can be
useful if the property only reads information and can't change information. If a property only reads
information, it's called a read-only property . Here is a simple example of a read-only property that
you add to the Cannon class:
Object.defineProperty(Cannon.prototype, "center",
{
get: function () {
return new Vector2(this.currentColor.width / 2,
this.currentColor.height / 2);
}
});
As you can see, you provide three parameters to the defineProperty method: a prototype, a name,
and an object. The name of this property is center . Its goal is to provide the center of the sprite
representing the cannon. Because it isn't possible to change the value of the center, this property
has only a get part. This is reflected in the object that is passed as the third parameter, which
contains one variable, get , that points to a function. Here is how you can use this property:
var cannonCenter = cannon.center;
Easy, isn't it? Similarly, you can add a property that provides the height of the cannon, as follows:
Object.defineProperty(Cannon.prototype, "height",
{
get: function () {
return this.currentColor.height;
}
});
You can even define a property ballPosition that calculates the position at which the ball should be:
Object.defineProperty(Cannon.prototype, "ballPosition",
{
get: function () {
var opposite = Math.sin(this.rotation) *
sprites.cannon_barrel.width * 0.6;
 
Search WWH ::




Custom Search