Created
September 1, 2012 21:19
-
-
Save BiggerNoise/3587687 to your computer and use it in GitHub Desktop.
A better javascript namespace/module pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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