Javascript: Using Namespaces

I'm not really too familiar with the concept of "namespaces," but essentially the gist seems to be that you want to avoid conflicts with existing structures that share the same name as your structures.

This might happen, for example, if you import a "library" of javascript functions.

You might have created a function called "displayCharacter()" or used a variable name like "hitpoints" without knowing that a javascript game library that you imported also has the same function name or variable name. In another case, maybe you are not so creative in your function names and you are prone to repeat usage of them -- ex. displayResult().

So, a way to avoid this might be to create your own unique "namespace" -- a sort of envelope that will hold some or all of the pieces of your specific program inside. The envelope is actually a new javascript object that you create, and then you sort of insert the objects into that enveloping namespace object using dot notation.

To set up a namespace, you would write a simple line of code like this:

var MyGame = MyGame || {};

What this statement does is it checks to see if the object "MyGame" already exists, and if it does not, then it creates a new blank object "{}". The resulting object is assigned to the variable name "MyGame," which, if it already exists is redundant, but if it does not exist creates your new empty namespace.

Now, that you have your namespace "MyGame", you can start inserting the parts of your program into the namespace using dot notation.

MyGame.name = "Dragon Magic";
MyGame.board = Object;
MyGame.score = 0;
MyGame.board.width = 200;
MyGame.board.height = 100;
MyGame.board.draw = function () {
  // code that draws the board on the screen

And, of course, you can also then refer to the variables and functions using the same namespace and dot notation.

alert("Welcome to " + MyGame.name + "!");

No comments :

Post a Comment