Categories
JavaScript

Javascript patterns: namespacing your objects.

Avoid clustering the global scope.

Start with uppercase (recommended):

var MYAPP = MYAPP || {};

To be able to construct objects with several levels of deepness, use the following utility function:

var UTILITIES = UTILITIES || {};
UTILITIES.namespace = function (ns_string) {
var parts = ns_string.split(‘.’),
parent = MYAPP,
i;

// strip redundant leading global
if (parts[0] === “MYAPP”) {
parts = parts.slice(1);
}

for (i = 0; i < parts.length; i += 1) { // create a property if it doesn't exist if (typeof parent[parts[i]] === "undefined") { parent[parts[i]] = {}; } parent = parent[parts[i]]; } return parent; };

Leave a Reply

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