Consider:
var module = {};
(function(exports){
exports.notGlobalFunction = function() {
console.log('I am not global');
};
}(module));
function notGlobalFunction() {
console.log('I am global');
}
notGlobalFunction(); // Outputs "I am global"
module.notGlobalFunction(); // Outputs "I am not global"
What’s going on here? I get that if you call notGlobalFunction(), it will just call the second function.
But what is var module = {} doing? And why is it called again inside the first function?
It says this is commonly known as a self-executing anonymous function, but what does that mean?
Immediately invoked functions are typically used to create a local function scope that is private and cannot be accessed from the outside world and can define its own local symbols without affecting the outside world. It’s often a good practice, but in this particular case, I don’t see that it creates any benefit other than a few more lines of code because it isn’t used for anything.
This piece of code:
Would be identical to a piece of code without the immediate invocation like this:
The one thing that is different is that in the first, an alias for
modulescalledexportsis created which is local to the immediately invoked function block. But, then nothing unique is done with the alias and the code could just as well have usedmodulesdirectly.The variable
modulesis created to be a single global parent object that can then hold many other global variables as properties. This is often called a "namespace". This is generally a good design pattern because it minimizes the number of top-level global variables that might conflict with other pieces of code used in the same project/page.So rather than make multiple top level variables like this:
One could make a single top level variable like this:
And, then attach all the other globals to it as properties:
This way, while there are still multiple global variables, there is only one top-level global that might conflict with other pieces of code.
Similarly, an immediately invoked function creates a local, private scope where variables can be created that are local to that scope and cannot interfere with other pieces of code:
Passing an argument into the immediately invoked function is just a way to pass a value into the immediately invoked function’s scope that will have its own local symbol: