Creating a namespace in JavaScript

· Leave a comment · in JavaScript

If you don’t namespace your code – you should.

It not only encloses the code but also gives it a unique name for reference.

This avoids “code collision”, where two like named objects or functions can break your code.

This isn’t an elaborate explanation of namespacing, there’s an abundance of detailed info out there.

Creating the namespace
Most sites have a “master” namespace, usually the name or initials of the company. Here we will use TGC.

Sometimes it will be an empty object, other times not.

You can then build on that master namespace to create sub-namespaces that include specific functions.

They are usually named by function. But make sure to make the name as agnostic as possible. We are going to use “slideshow”, which if the style or functionality changes, is still valid. A wrong name would be “verticalSlideshow” – what if later it needs to be horizontal?

The first line below checks for the master namespace and if it does not exist, creates it.

The second line is our “slideshow” namespace.

if(typeof TGC==="undefined" || !TGC) TGC={};
if(typeof TGC.slideshow==="undefined" || !TGC.slideshow) TGC.slideshow={};

Now we have an empty TGC.slideshow namespace instance that we can fill.

I usually fill it with default values first, then an init.

TGC.slideshow = {
    defaults: {
        "orientation": "horizontal",
        "autoPlay": "false",
        "autoPlayInterval": 5000
    },
    init: function(){
        //do something
    }
}

Now when you want to access a default value you can use dot notation:

TGC.slideshow.defaults.autoPlay

And when you want to call the init function:

TGC.slideshow.init()

You can do much, much more like pass settings, make a function self-executing, etc. This is just a simple outline.

Great books are available on JavaScript.

This entry was posted in JavaScript and tagged , .
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">