JavaScript Design Patterns Help Needed: Loose Augmentation of Modules

(function(){

})();

is a self-invoking anonymous function. In your case, it handles the "my" object parameter: it does something to "my" and then returns it back.

In your case the "my" parameter the function receives is "(MODULE || {})".

The && and || operators are called short-circuit operators. || will return, if "MODULE" object exists, the "MODULE" object, otherwise, an empty object will be created to be used inside the function. The function will do whatever it does to that object, which will became the returned "MODULE" object.

It works by creating a closure: as long as MODULE exists (it's not garbage collected) so does the self-invoking anonymous function along with its state at the time of assignment. This makes any capabilities added to be persistent.


The right-hand-side is called immediate function. To understand how it works, let's break it down a bit:

  1. (...)() we can call a function by name, i.e. f(). But, instead of function name, we can place any expression that resolves to a variable of type function. In our case, the first set of parenthesis merely encloses an expression. The second set is function call operator. Ultimately, (f)() is equivalent exactly to f()

  2. The second step is to provide an anonymous function inside the first parenthesis set. The result is: (function(){})(). The anonymous function is perfectly of type function. This causes the function to be created, executed and discarded all in the same statement.

  3. The second set of parenthesis which is the function call operator can accept parameters inside it, which is in our case MODULE || {}. This expression means: if MODULE is defined, use it, otherwise, create a new empty one.

  4. The parameter is passed to the anonymous function as an argument called my and the anonymous function returns, um, my. This causes the anonymous function to evaluate to my and in effect: (my)(MODULE || {}).

  5. The effect is MODULE is self contained and causes no name clashes with outside variables. While, in the same time, it has access to outside variables.

I hope this clears it :)