Javascript Namespacing

Ever wonder how those wonderful java script libaries never manage to override each other even when used concurrently?

They try to be friendly neighbours by using:

JavaScript NameSpacing

It is not common to use NameSpacing in JavaScript. Can't blame everyone, they just used JavaScript for basic validations and some client side scripting only. But now, with Web 2.0 booming at a pace faster than ever, I guess is a right time to start introducing NameSpacing in your JS codes. It is critical when you perhaps build a library for others to make use of. NameSpaces prevent duplicate function problems just like packaging in Java or namespacing in C#.

Namespacing can be done very simple-like in a manner that is painless and nice-looking. And I know “looking-nice” should generally not be a determining factor on how your code should be written, but this indeed has some benefits as well.

Extending the namespace

Perhaps the best way of setting up an application object is as demonstrated below:

var NameSpaceName = function() {
    return {
        YourMethod1 : function() {
            // your function implementation
        },
        YourMethod2: function() {
            // your function implementation
        },
        YourMethod2: function() {
            // your function implementation
        }

        // you can declare variables and private functions as well!
        var xyz;
        function alertUser()
        {
            alert('Hey Dude!');
        }
    };
}();

There are other ways to implement it. Feel free to share. :)

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License