Gabi Purcaru
Gabi Purcaru

Reputation: 31524

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?

Upvotes: 5

Views: 182

Answers (2)

anthony sottile
anthony sottile

Reputation: 69844

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.

Upvotes: 1

AshHeskes
AshHeskes

Reputation: 2324

The part your missing is that javascript is a case sensitive language so

Narcissus != narcissus; 

He is adding Narcissus to the global scope by omitting the var keyword, or Narcissus is already available in the global scope, or Narcissus has already defined in the scope of where this function is being called.

Then defining it as the object narcissus inside the anonymous function.

I cannot tell you why he is doing this, but it seems like he might already be inside a scope where this is referring to an object, and he want to set the key hostGlobal to the global object not the currently scoped object.

That is why he is running it as an anonymous function, as they are executed in the global scope not function scope. So in his code hostGlobal: this is referring to the global object.

Of course he could just use hostGlobal: window, unless this code is also being run in non browser environments such as node.js where the global object is global not window. So he might be doing it as a very unintuitive method of achieving.

hostGlobal: ( global === undefined )? window : global  

Hope this helps

Upvotes: 0

Related Questions