Why assign an IIFE variable?

I used IIFE in JavaScript and AngularJS and used the following structure:

Method 1:

 //IIFE Immediately Invoked Function Expression (function () { }()); 

However, I often saw the following: where the variable is assigned IIFE

Method 2:

 //IIFE Immediately Invoked Function Expression assigned to doStuff variable var doStuff = (function () { }()); 

NOTE. This question is NOT about what a template is or what IIFE is. This relates specifically to why the return variable on IIFE and its relation to Angular methods should be used.

In Angular, Method 1 works fine, but in many of the original JS examples, I can see that Method 2 is used. My assumption is that everything that was enclosed in doStuff will be accessible through it and called. However, I am not 100% sure about the exact reasoning or differences between the two methods and need some help to understand when to use the different methods?

+5
source share
1 answer

The reason for method # 2 is that you will find code inside IIFE that returns something (usually, but not necessarily, an object or function). What IIFE returns is what ends with the assignment. For instance:.

 //IIFE Immediately Invoked Function Expression assigned to doStuff variable var doStuff = (function () { var privateInformationForDoStuff = 0; function doStuff() { console.log(++privateInformationForDoStuff); } return doStuff; }()); 

Here the variable ends with a reference to a function, which each time it is called gives us a number higher than in the previous time. IIFE exists to ensure that nothing can change the privateInformationForDoStuff variable, it is completely closed to the doStuff function.

A common use of this is to create objects with various functions on them, sometimes called modules, which can also have personal information that is available only in the "module":

 var MyApp = (function() { var privateModuleInformation; var morePrivateModuleInformation; // ... function doThis() { // ... } function doThat() { // ... } function doTheOther() { // ... } return { doThis: doThis, doThat: doThat, doTheOther: doTheOther }; })(); 
+7
source

Source: https://habr.com/ru/post/1205018/


All Articles