Javascript namespace example

author(s): Ryan Moore

HTML

<div id='result'></div>

JavaScript

var Util = {};

Util.namespace = (function (root) {
    var ns_regex = /^([\$\_a-z][\$\_a-z\d]*\.?)+$/i; 

    function genNS(ns) {
        if (!ns.match(ns_regex)) {
            return;
        }
        
        // split the namespace by the periods
        ns = ns.split('.');
        var base = root;
        for (var i = 0; i < ns.length; i++) {
            // and create a new object for each 
            base[ns[i]] = base[ns[i]] || {};
            base = base[ns[i]];
        }
        
        return base;
    }
    
    return function (ns) {
        // allow multiple arguments to be passed
        var args = Array.prototype.slice.call(arguments);
        var ret = [];
        while (args.length) {
            ns = genNS(args.shift());
            if (ns) {
                ret.push(ns);
            }
        }
        
        if (ret.length == 0) {
            return;
        }
        
        if (arguments.length == 1) {
            return ret[0];
        }
        
        return ret;
    }; 

} (this));

// Example of declaring a new namespace using this method
Util.namespace('Namespace1.Namespace2'); 

// also can use the following to define multiple namespaces at once:
// namespace('Namespace1.Namespace2', 'Namespace1.Namespace3'); 

// example class using the new namespace
Namespace1.Namespace2.myClass = function($) {

    function init() {
        $('#result').text('Namespace worked!');
    }

    return {
        init:init
    }    
}($);

// call the init method when the page loads
$(function(){
    Namespace1.Namespace2.myClass.init();
});