lundi 1 août 2016

How is IIFE better than "named function declaration" in preventing name collision?

I have read on stackoverflow that the benefit of IIFE pattern in implementing modules instead of just "named function declaration" is that, in large projects, it can prevent name collisions. However, it seems to me that IIFE is no more better or worse than a named function declaration for preventing name collision.

Consider 2 methods of writing a library which exposes a name called "GenericModuleName":

IIFE approach

var GenericModuleName = (function () {
    return ObjectWhichHasPublicMethod;
})();

Named function declaration approach

function GenericModuleName() {
    return {
        PublicMethod : function () { privateMethod(); }
    }
};

In both cases, if the user of the library coincidentally also has a function named GenericModuleName, there will still be a name clash, isn't it? So how is IIFE better than "named function declaration" in preventing name collision?

Aucun commentaire:

Enregistrer un commentaire