Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zephraph
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zephraph/9e07e0fa82cf750f243b to your computer and use it in GitHub Desktop.
Save zephraph/9e07e0fa82cf750f243b to your computer and use it in GitHub Desktop.
Javascript namespacing made simple
Namespace = function(scope, definition) {
var root = typeof GLOBAL !== 'undefined' ? GLOBAL : window;
scope = scope.split('.');
for(var i = 0; i < scope.length; ++i) {
if(typeof root[scope[i]] === 'undefined')
root[scope[i]] = {};
root = root[scope[i]];
}
switch(typeof definition) {
case 'function':
definition.apply(root);
case 'object':
for(var key in definition)
root[key] = definition[key]
}
return root;
}
Namespace('some.namespace', function() {
// 'this' is bound to the 'some.namespace' object
this.namespacedFunction = function() {
console.log('I live in some.namespace');
}
});
Namespace('some.other.namespace', {
// This object will be joined into the namespace
func: function() {
console.log('I live in some.other.namespace');
}
});
// The namespace can also be accessed directly
Namespace('some.other.other.namespace').fun = function() {
console.log('WEEEEEEEEEEEEEEEEEE!!!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment