Skip to content

Instantly share code, notes, and snippets.

@mattlo
Last active August 18, 2016 16:53
Show Gist options
  • Save mattlo/4608611 to your computer and use it in GitHub Desktop.
Save mattlo/4608611 to your computer and use it in GitHub Desktop.
JavaScript Namespace Generator - Create namespaces on the fly using dot delimiters (accessible via dot notation).
var Namespace = (function (global) {
"use strict";
// empty object to verify namespaced objects
function Namespace() {}
return function (namespace) {
var chunks = namespace.split('.'),
lastObjRef = global,
i;
// iterate over chunks
for (i = 0; i < chunks.length; ++i) {
if (typeof lastObjRef[chunks[i]] !== 'undefined') {
if (lastObjRef[chunks[i]] instanceof Namespace === true) {
lastObjRef = lastObjRef[chunks[i]];
// next iteration
continue;
} else {
throw new Error("Non Namespace Object exists, cannot create namespace.");
}
}
// create new object
lastObjRef[chunks[i]] = new Namespace();
// assign new last object reference
lastObjRef = lastObjRef[chunks[i]];
}
// return reference to prevent double typing
return lastObjRef;
};
}(this));
@mattlo
Copy link
Author

mattlo commented Jan 23, 2013

Example usage:
Namespace('hello.world').Class = function () {alert('test');}
hello.world.Class();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment