Search code examples
javascriptsyntaxanonymous-functionsnap.svgself-invoking-function

Ending a Javascript function with a left curly brace a mistake?


I've only been a dabbler in simple Javascript until recently. In the last couple weeks I've been trying to learn more advanced aspects of it. Coming from a classical programming background, prototypes in Javascript have thrown me for a loop more than a few times...

While studying the Snap.svg API (trying to learn technique) I found the following:

    (function (glob, factory) {
    // AMD support
    if (typeof define == "function" && define.amd) {
        // Define as an anonymous module
        define(["eve"], function (eve) {
            return factory(glob, eve);
        });
    } else if (typeof exports != 'undefined') {
        // Next for Node.js or CommonJS
        var eve = require('eve');
        module.exports = factory(glob, eve);
    } else {
        // Browser globals (glob is window)
        // Snap adds itself to window
        factory(glob, glob.eve);
    }
}(window || this, function (window, eve) {

This is in the latest version of Snap, starting on line #423

At first, I thought it was an anonymous self-invoking function, then I noticed the open curly brace. I've looked down through the code that follows and cannot account for the closing brace. Further, searching for the occurrences of curly braces in the 8k+ lines of code (using notepad++) indicates one more open brace than closing. Also, when I collapse the first line in the snippet, the entire remainder (almost 8000 lines) of code collapses. The last line of code in the API ends with:

}));

Is it possible the missing closing parenthesis on the function got pushed to the end of the file? That could maybe account for the double closing parenthesis at the end of the file (second snippet)? I'd report the error on github, but I'm assuming I'm reading this wrong.

I'd appreciate if someone could explain what's going on.


Solution

  • That top chunk of code is actually closed by the final })) and it is not a mistake.

    What you're looking at is a UMD wrapper for the code so that it can be loaded by global reference, AMD, and CommonJS.