javascriptiife

If an IIFE contains just one variable declaration that is immediately exported to global scope, why bother with it?


It's late in the evening here so I may not be functioning very well, but I found this piece of code and I can't seem to figure out why it's used like this (NOTE: I understand what it does, what I don't understand is the meaning behind it).

(function() {

    var narcissus = {
        options: {
            version: 185,
        },
        hostGlobal: this
    };
    Narcissus = narcissus;
})();

Self-executing anonymous functions are used to avoid pollution of the global namespace, but this code doesn't need to introduce other variables than Narcissus so it could have very easily be rewritten as Narcissus = {...};. Some possible reasons I can think of are future-proofing of the code or implementation flaw. Is there something I fail to see?


Solution

  • From a maintainability standpoint it allows the author to later add code in a Closure scope that doesn't get leaked between the creation of narcissus and the assignment of Narcissus. Though in this case there isn't any code there so I don't see any gains other than the this stuff mentioned above.