Skip to Navigation or
Skip to Content

JavaScript Name Spacing

Feeds

RSS Feed

<< January | February | March >>

Wednesday, 3rd February 2010

This is just a quick article to demonstrate a quick bit of JavaScript name-spacing.

Why would you do this? Well, this allows you to put functions and variables inside of an identifier. It acts like a "box of stuff" and prevents variable and function name conflicts. It also supplies a neat way to organise and access your code in logical blocks.

If you're interested, here's how you do it.

Before:

var SayHello = function(name) {
    alert("Hello " + name + "!");
}
SayHello("Steve");

After:

var MyNamespace = (function() {
    return {
        SayHello : function(name) {
            alert("Hello " + name + "!");
         }
    };
}());
MyNamespace.SayHello("Steve");

Obviously, in this example it's all a bit basic, but if you had JavaScript functions that you'd like to group together, this is a great way to do it - not a genuine name-space, but some distance towards organising your code.

 

You Are Here: Home » Blog » JavaScript Name Spacing

 

I use a cookie on this website. This cookie doesn't contain or relate to any personal information and it isn't shared with any other website, it just ensures that I don't count you more than once in my website statistics. The Privacy and Electronic Communications Regulations require me to ask your permission to use this cookie, so please indicate below that you are happy for me to do this - I will remember your selection with a cookie, so if you accept I won't ask again...