Skip to content

Instantly share code, notes, and snippets.

@zephraph zephraph/Namespace.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.