One note about my code snippets. For simplicity I will be concatenating what would in a real application be multiple .js files into a single code snippet. I’ll use comments to show you where the files break.
So let’s imagine you are creating a helper function to do something really useful, like add two numbers together.
We have defined this function in the global scope, let’s do the right thing and wrap a function scope around each file.
Now the two scopes can’t see each other or interact with each other. So how can we make our add function available to the rest of our application without just throwing it in the global scope.
I present to you Namespaces.
Basically a namespace is an object that sits in the global scope. They can be nested and since you should be naming them much more uniquely than you would a regular variable the chances of conflicting with another library are slim.
So let’s expose our add function through a namespace.
The WinJS.Namespace object is itself a namespace, defined in the base.js I mentioned above, which is why we are able to just call off to it. Once we define our own namespace we can then call it in any later code in the same way.
Another interesting feature of Namespaces is that they are composed, so if you define the same Namespace twice instead of overwriting it you add to it.
Suppose we now want to add a subtract method, but we want it to be in a separate file from our add method. A better example, which we are using at Code52, suppose you have two implementations for your data access layer. You want them in the same namespace but in separate physical files.
This is super useful and kudos to Microsoft for making it work that way.
To demonstrate this I will keep a running total of all the sum operations, and add a new function to return that total.
The runningTotal variable and the adjustTotal method are both local to the helpers.js file and inaccessible outside of it. However, the add and total functions that we are exposing through the namespace have captured and retained the scope in which they were define and therefore still have access.
So that is a quick introduction to namespaces. I have only shown exposing functions, but variables can be exposed as well. What I have shown here is most similar to a static class in C#.
Next time I will look at WinJS.Class and how you can use it to create class definitions.