Skip to content

Instantly share code, notes, and snippets.

@BiggerNoise
Created September 1, 2012 21:19
Show Gist options
  • Save BiggerNoise/3587687 to your computer and use it in GitHub Desktop.
Save BiggerNoise/3587687 to your computer and use it in GitHub Desktop.
A better javascript namespace/module pattern
app = (function () {
var Namespace = function () {
}
var Module = function () {
}
Namespace.prototype.createModule = function () {
var m = new Module;
if(arguments.length > 0)
m.extend.apply(m, Array.prototype.slice.apply(arguments));
return m;
};
Module.prototype.extend = function (fn) {
var argArray,
results,
resultKey,
namespace = this;
argArray = Array.prototype.slice.apply(arguments).slice(1);
this._private = this._private || {};
results = fn.apply(this._private, argArray);
for(resultKey in results) {
if(results.hasOwnProperty(resultKey)) {
namespace[resultKey] = results[resultKey];
}
}
return this;
}
var app = new Module();
app.namespace = function (ns) {
return ns ? ns : new Namespace();
}
app.createModule = Namespace.prototype.createModule; // app is special since it is both a module (for functionality) and a scope
return app;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment