Search code examples
javascriptdesign-patternsmodule-patternshorthand-if

JavaScript Design Patterns Help Needed: Loose Augmentation of Modules


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


Solution

  • (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.