According to the Closures concept it will store the variables of the outer lexical environment for future execution of its inner function. For example:
function makeYounger(age) {
function b() {
console.log("Original age is :" + age);
}
b();
return(function() {
return age / 2;
});
}
var displayAge = makeYounger(20);
console.log(displayAge());
In the above scenario, age
is preserved by the Javascript engine to execute the inner function present in the return method.
Here comes the IIFE:
(function(window) {
var greeting = "Hello";
var fNameSpace1 = {
name : "Appu",
callName : function() {
console.log(greeting + fNameSpace1.name);
}
};
window.doer = fNameSpace1;
}) (window);
fNameSpace1.callName(); //To execute the inner function
In the above scenario according to the closures concept the variables greeting
and fNameSpace1.name
will be stored for future execution of the callname()
function. Instead we are making use of the window
object. I am confused why we are going with window
if we have closures?
An IIFE is just one specific way to A) Create a closure over the context in which it's defined, and B) Create a context in which to create other closures.
So it can be used outside the IIFE, by referring to it via the
doer
global thatwindow.doer = ...
creates.There are dozens of different ways to do this. One of them does it by assigning to
window
like that. Another does it by returning the value and using avar
statement:but again, there are dozens of different formations. The author of that particular one just preferred to write to a property on
window
as the way to create the global.