Skip to content

Instantly share code, notes, and snippets.

@roundcorners
Created January 24, 2012 21:19
Show Gist options
  • Save roundcorners/1672777 to your computer and use it in GitHub Desktop.
Save roundcorners/1672777 to your computer and use it in GitHub Desktop.
Namespacing method
/**
* @name: [namespace] adds properties to the current namespace object.
* @argument[0] [name_str] {String} the propert(y/ies) we want to add.
* @returns {Object} the augmented namespace.
*/
// Check for the namespace, create it if not already defined
(MyNamespace || MyNamespace = {}).namespace = function(name_str) {
// Split the name string into an array of parts
var parts = name_str.split('.'),
part, i, len,
// Quick reference to the namespace object
parent = this;
// For each part that is not a property of the namespace, create an empty object keyed by the part
for (i = 0, len = parts.length; i < len; i++) {
if (typeof parent[parts[i]] === 'undefined') {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
// And return the augmented namespace object
return parent;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment