Skip to content

Instantly share code, notes, and snippets.

Created March 10, 2011 13:39
Show Gist options
  • Save anonymous/864101 to your computer and use it in GitHub Desktop.
Save anonymous/864101 to your computer and use it in GitHub Desktop.
HowTo proper namespacing in JS
// Initialize namespaces ---------------------
if (!window.mm) {
mm = {};
}
// avoid window. use this if you "think" you are in root closure. makes encapsulation possible and code executable without DOM (like node...)
if (!this.mm) {
mm = {};
}
// or (freaky) don't try to understand! ;)
mm = this.mm || {};
// Writing constructors or general functions in namespace:
// Instead:
function MapEditor(mapContainerId) {
// private properties
var i18n = null;
var googleMapOptions = {
...
// do:
mm.MapEditor = function(mapContainerId) {
...
instance = new mm.MapEditor(...)
// var xy; is only local to current function call, but all called functions get it too!
// From the JS Godfather: http://www.crockford.com/javascript/private.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment