Skip to content

Instantly share code, notes, and snippets.

@andrewgunn
Last active December 15, 2015 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgunn/5221212 to your computer and use it in GitHub Desktop.
Save andrewgunn/5221212 to your computer and use it in GitHub Desktop.
;
(function (root, undefined) {
'use strict';
var toString = Object.prototype.toString;
if (toString.call(root.namespace) === '[object Function]') {
return;
}
root.namespace = function (ns, parent) {
var parts,
index,
length;
if (toString.call(ns) !== '[object String]') {
throw new Error('Invalid namespace: ' + ns);
}
parts = ns.split('.');
parent = parent || root;
for (index = 0, length = parts.length; index < length; index += 1) {
if (typeof parent[parts[index]] === 'undefined') {
parent[parts[index]] = {};
}
parent = parent[parts[index]];
}
return parent;
};
})(this);
// var modules = namespace('app.modules'); -> app.modules = {}
// var moduleA = namespace('app.modules.moduleA'); -> app.modules.moduleA = {}
// var moduleB = namespace('moduleB', modules); -> app.modules.moduleB = {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment