Edit for clarity - @Qantas94Heavy - I understand what it is "saying" or supposed to do, what I don't understand is why & more importantly how it works:
I was reading an advanced tutorial on the JS Module Pattern, and it gave this example:
var MODULE = (function (my) {
// add capabilities...
return my;
}(MODULE || {}));
The thing that is bugging me (and I need your help with) is the last statement:
(MODULE || {}));
i'm having trouble understanding the syntax rules behind this that make it possible. After doing some searching for keywords, "JavaScript Module Syntax", and "Module Pattern Short Hand" I found that I'm still not quite understanding the foundation behind this.
Would someone please explain or point me in the right direction for grokking this/gaining a deeper understanding?
Sincerely, gggi
(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:
(...)()
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()
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.
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.
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 || {})
.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With