JavaScript Namespace

I normally put my JavaScript function/classes/other things in namespaces. Namespacing your JavaScript is good, it avoids conflicts between scripts on the page and keeps the global namespace clean. I could go into more detail, but luckily it has been done for me.

Declaring namespaces, and checking they exist before using them is a bit of a pain. You might find yourself doing something like:

if(!window.com) window.com = {};
if(!com.mycompany) com.mycompany = {};
if(!com.mycompany.mypackage) com.mycompany.mypackage = {};

…and then add things to it like:

com.mycompany.mypackage.myfunction = function() { return 138; };

To make things worse, if your webpage includes a different script that uses slightly different namespace, say "com.mycompany.mypackage2" you’ll have to check again that the objects "com" and "com.mycompany" already exist.

The following function allows you to use a namespace, without having to manually go through the throws of checking each "space" exists and creating an empty object for each level.

/**
 * I declare a namespace if it doesn't already exist.
 *
 * @param {String} ns The namespace to create/use
 * @param {Object} parent (Optional) The parent object onto which this namespace will be attached.
 * @return True if the namespace was created successfully.
 * @type Boolean
 */
function namespace(ns, parent) {

	if(!parent) {
		parent = window;
	} else {
		// Parent must be an object
		if(typeof(parent) != 'object') {
			return false;
		}
	}

	var names = ns.split('.');

	if(!names.length) {
		return true;
	}

	var name = names[0];

	if(!parent[name]) {
		parent[name] = {};
	}

	if(names.length > 1) {
		names.shift();
		return namespace(names.join('.'), parent[name]);
	}

	return true;
}

…and is used like so:

namespace('com.mycompany.mypackage');
com.mycompany.mypackage.myfunction = function() { return 138; };

One thought on “JavaScript Namespace

  1. Looking at this again, it would actually be useful if the function actually returned the namespace object it created so you can start adding functions to it. The namespace could then become a local variable, which would be much better for minification.

    You’d have something like:

    (function() {
    var ns = namespace('com.mycompany.mypackage');
    ns.myfunction = function() { return 138; };
    })();

Leave a Reply

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

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>