Game Development Reference
In-Depth Information
Variables as Namespaces
Namespaces are commonly used in programming languages to provide some structure for where
classes belong. Many programming languages have namespace support baked in the language
specification. JavaScript isn't one of those languages, but it's very easy to use the existing
functionality in the language to set up something similar.
You've seen in the example code that variables are groups of objects. These objects can be object
literals, strings, numbers, or even functions. Because a class is defined by a function in JavaScript,
you can group classes together in a variable, making that variable serve as a namespace. For example,
suppose you want to create a JavaScript game engine that contains all the generic classes and
objects you've built in this topic. Let's call this game engine powerupjs . You can start defining your
classes as follows:
var powerupjs = {
GameObject : function(layer, id) {
...
},
GameObjectList : function(layer, id) {
...
}
};
Now, whenever you want to use the class GameObject , you type powerupjs.GameObject . In the
JavaScript code, this will make it clear to the user that GameObject belongs to the powerupjs
namespace. This is great, but it means you have to put all your classes in a single JavaScript file,
and this doesn't really improve the readability of your programs. Let's investigate how you can do
this in a smarter way.
A Design Pattern for Namespaces
To make using namespaces easier in JavaScript, you use a design pattern . Chapter XX briefly talked
about design patterns in the discussion of singletons (classes that allow only a single instance).
This singleton design pattern was used as follows:
function MySingletonClass_Singleton () {
...
}
// add methods and properties here
MySingletonClass_Singleton.prototype.myMethod() = function () {
...
};
...
var MySingletonClass = new MySingletonClass_Singleton();
// now we can use the variable as a single instance
MySingletonClass.myMethod();
 
Search WWH ::




Custom Search