Game Development Reference
In-Depth Information
is filled with all the classes that are supposed to be in the
powerupjs
namespace. You can make this
even nicer by using smart JavaScript syntax. Consider the following class definition:
var powerupjs = (function (powerupjs) {
function Vector2(x, y) {
this.x = typeof x !== 'undefined' ? x : 0;
this.y = typeof y !== 'undefined' ? y : 0;
}
// etc.
powerupjs.Vector2 = Vector2;
return powerupjs;
})(powerupjs || {});
Here you rename the
module
parameter to
powerupjs
for clarity; and instead of passing an empty object
literal, you pass the expression
powerupjs || {}
. This expression results in
powerupjs
if that variable is
defined, or an empty object literal otherwise. You add this namespace design pattern to all the generic
game classes. Regardless of the order in which these classes are added to the namespace, the first
time this is done you start with an empty object literal, and after that, the
powerupjs
variable is defined
and supplemented with the rest of the classes. The example code belonging to this chapter includes a
folder called
powerupjs
; in this folder are all the generic game classes, all of which are in the
powerupjs
namespace. The remaining examples in this topic reuse the
powerupjs
module (or library) as a basis for
the example games.
The namespace pattern is a very useful pattern for grouping related classes together. Whenever
you're building a complex application, it's a good idea to use namespaces. That way, you clearly
show the users of your code how the classes are related to each other. You can be even more
extreme and group namespaces in other, bigger namespaces, using exactly the same design pattern.
Namespaces also provide a bit of extra security. For example, have a look at the following class
definition in a namespace:
var powerupjs = (function (powerupjs) {
function GameStateManager_Singleton() {
this._gameStates = [];
this._currentGameState = null;
}
// add methods/properties here
...
powerupjs.GameStateManager = new GameStateManager_Singleton();
return powerupjs;
})(powerupjs || {});
Search WWH ::
Custom Search