Thursday, February 17, 2011

JavaScript Namespaces

As your JavaScript applications become more complex, it is imperative that you namespace your scripts to avoid naming conflicts and avoid polluting the global namespace. (i.e., the window object)


JavaScript has no built-in support for namespaces, but you can simulate them by assigning your functions as properties of an object.


var NameSpaces = {
    Register: function (namespace) {
        var nsParts = namespace.split(“.”);
        var root = window;

        for (var i = 0; i < nsParts.length; i++) {
            if (typeof root[nsParts[i]] == “undefined”)
                root[nsParts[i]] = new Object();

            root = root[nsParts[i]];
        }
    }
};

NameSpaces.Register(“My.Namespace”);


My.Namespace.myFunction = function() {

};


You can now call your new function as My.Namespace.myFunction(), which is uniquely scoped to the window.My.Namespace object, and safely avoid conflict with any other “myFunction” that might appear in another loaded script. Namespacing your functions also keeps the global namespace clean and uncluttered.


Thanks to Michael Shwarz for the Register function in the above closure: http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx


No comments:

Post a Comment