Javascript: namespacing
javascript, namespaces
Solution
Actually, it is all about semantics. If you are breaking your code apart multiple files and plan on utilizing a general namespace then doing something like this is a little bit easier:
The reason why I enjoy this method is that it is much more modular and allows for code to be broken apart into multiple files and then just as easily compressed them into one without dependency issues (unless your namespaced functions depend on one another)
The downside to this is that it can feel a bit messy at times if used incorrectly -- Which I guess can apply to anything.
In your namespace file
var Namespace = {};
In your other JavaScript files that are using the namespace
var Namespace = Namespace === undefined ? {} : Namespace;
Namespace.stuff = function () {
var private = 'foo';
function private_func() {
};
this.public = 'bar';
this.public_func = function () {
}
};
Some practical application would be:
GUI.js
// Some general GUI
var GUI = {
'MAX_WIDTH': $(window).width(),
'MAX_HEIGHT': $(window).height()
};
Toolbar.js
GUI.Toolbar = function (id) {
var self = this;
function init_visuals() {
$(id).click(function () {
self.alert_broken();
});
};
function initialize() {
init_visuals();
};
this.alert_broken = function () {
alert('Broken!');
};
initialize();
};
Menu.js
GUI.Menu = function () {
}; GUI.Menu.prototype = new GUI.Toolbar();
Now, singletons -- That's whole another argument.
Problem
I'm currently using the following pattern to create namespaces and singleton objects in Javascript: ``` var Namespace = function () { var priv = { privateVar1: '', privateVar2: '', privateFunction1: function () { //do stuff [...] }, [...] }; var pub = { publicVar1: '', publicFunction1: function () { //do stuff with private functions and variables priv.privateVar1 = priv.privateFunction1(pub.publicVar1); [...] }, [...] }; return pub; }(); ``` I hope you get the idea. Is there a way to create namespaces that you think is cleaner or better (explain why)?