… yes every time a longer title

What we want

A tidy JS code = clean global scope = well organized functions in boxes (modules) independant.

What is Cross-Reference problem ?

Cross-reference in JS is when you accidentally override a function or variable ; because there is another function or variable with the same name.

Cross-reference can be frequent in javascript, because it just has function isolation. So a variable in global scope is not safe, and you must keep the number of global variable as low as possible.

You have to ban global variable in your code

☑ But don’t fear: module pattern solve this !

Private function

Javascript has no notion of private inside object (change coming in ES6).

☑ Module pattern solve this today !

See module like a functions container : it isolate all functions inside from the global scope.

So the Module pattern

A module allow you to define functions in a scope (remember JS is function scoped).

Define a simple module :

var myModule = (function () {
  // module code ...
  // All code here is scoped in myModule
})();

⤷ All inside the module is scoped in “myModule” which is the only variable in your global scope.
Module is a coding pattern that use an anonymous function to regroup generic function and allow to have private function inside module.
So your module should be prefixed to not use a common or reserved name (I prefix all mine with ‘app_‘) !

Let’s make it better : define private method or attribute and some public method :

var myModule = (function () {
  'use strict'; // I strongly advice to set strict mode in each module

  var privateMethod = function () {
    // private
  };

  var someMethod = function () {
    // public
  };

  var anotherMethod = function () {
    // public
  };

  return { // Return methods we want to be public
    someMethod: someMethod,      // NOTE here you can change the returned name, 
    anotherMethod: anotherMethod // but don’t : it’s useless and error prone
  };
})(); // Close your module

// And now you can call :
myModule.someMethod();

⤷ So you can organize your code in many modules containing methods dedicated to task

The module pattern should be used everywhere you can regroup generic functions.

Tips 2 : Use 1 singleton object for a tidy application

For storing variable/array/object to store your app parameters or state or wahtever should be stored you should use 1 object.

⤷ All your objects should belong in 1 singleton master object; I call it “app”. So everything about your application state/parameters is in a single app object (it may have method too); and everything else is in some modules.

Doing so, you will never have cross-reference problem, and the private of module pattern can help other developer to understand how to use your code.

More reading : Todd Motto : Mastering the Module Pattern