Skip to content

Instantly share code, notes, and snippets.

@warseph
Created December 19, 2012 14:37
Show Gist options
  • Select an option

  • Save warseph/4337096 to your computer and use it in GitHub Desktop.

Select an option

Save warseph/4337096 to your computer and use it in GitHub Desktop.
Somewhat functional javascript namespaces implementation
var namespace = function (name) {
'use strict';
var self, namespaces, i, max;
if (name.indexOf('.') >= 0) {
namespaces = name.split('.');
self = this;
for (i = 0, max = namespaces.length; i < max; i += 1) {
self = namespace.call(self, namespaces[i]);
}
} else {
if (this[name] === undefined) {
self = function (name) {
return namespace.call(self, name);
};
this[name] = self;
}
self = this[name];
}
return self;
};
//Examples
namespace('MyApp')('Namespace')('Test1')('Test2');
namespace('MyApp')('OtherNamespace')('Test1')('Test2');
namespace('MyApp.Just.Another.Way.To.Call.It');
//You can create a function in a namespace doing something like this:
namespace('MyApp')('Namespace')('Test1')('Test2').testFunction = function () {
'use strict';
console.log('hello!');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment