Reputation: 63
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?
Upvotes: 5
Views: 11230
Reputation: 1686
var module = {};
(function(exports){
exports.notGlobalFunction = function() {
console.log('I am not global');
};
console.log(exports === module); // Writes true into the console
}(module));
function notGlobalFunction() {
console.log('I am global');
}
notGlobalFunction(); // Outputs "I am global"
module.notGlobalFunction(); // Outputs "I am not global"
The following row declares a variable and assigns to it an empty object:
var module = {};
Among other things, it can be also used as namespace to prevent the pollution of the global scope.
The following row declares an anonymous function with a parameter named exports that will be available only inside the scope of the anonymous function itself:
(function(exports){
As already said, into the row above, the var exports is a parameter of the anonymous function it self and as we are going to see, it references (basically creates a local alias) that holds the same content that is inside the var module: this is because in Javascript objects are passed by reference.
The following rows:
exports.notGlobalFunction = function() {
console.log('I am not global');
};
assign a method (= function inside an object) to the notGlobalFunction property crated into the object {} referenced into exports and also stored into the var module. So, basically, in other words, the part .notGlobalFunction will be a property, or more precisely in this case, will store a method that is going to be owned by both the two object vars, module and exports. So with this code and as a consequence of the above explication (in javascript object are passed by reference) the same property will be also available into the var module too as will be the whole function that it will hold. So after executing the above code both the vars exports and module will store/reference the same object, in fact:
module =
{
notGlobalFunction: function() {console.log('I am not global');}
}
and
export =
{
notGlobalFunction: function() {console.log('I am not global');}
}
and if right after the following code:
exports.notGlobalFunction = function() {
console.log('I am not global');
};
you also do:
console.log(exports === module);
that is a strict comparison of the two objects, you will get true into the console because module and exports are basically storing/referencing the exact same object.
The following row passes to the parameter called exports of the anonymous function above, a reference to the empty object {} that was first stored into the var module with the code into the first row. So the var module here becomes an argument of the anonymous function above:
}(module));
so the object stored into the var module is passed as reference to the var exports, similarly to if we had done:
exports = module;
The rest of the code
function notGlobalFunction() {
console.log('I am global');
}
notGlobalFunction(); // Outputs "I am global"
module.notGlobalFunction(); // Outputs "I am not global"
basically aims to demonstrate and compare the different availability and behaviors of global and local scopes/namespaces: the comments already present into the code are self esplicative.
Follows the code snippet:
var module = {};
(function(exports){
exports.notGlobalFunction = function() {
console.log('I am not global');
};
console.log(exports === module); // Writes true into the console
}(module));
function notGlobalFunction() {
console.log('I am global');
}
notGlobalFunction(); // Outputs "I am global"
module.notGlobalFunction(); // Outputs "I am not global"
Upvotes: 0
Reputation: 707298
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:
(function(exports){
exports.notGlobalFunction = function() {
console.log('I am not global');
};
}(module));
Would be identical to a piece of code without the immediate invocation like this:
module.notGlobalFunction = function() {
console.log('I am not global');
};
The one thing that is different is that in the first, an alias for modules
called exports
is 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 used modules
directly.
The variable modules
is 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:
var x, y, z;
One could make a single top level variable like this:
var modules = {};
And, then attach all the other globals to it as properties:
modules.x = 5;
modules.y = 10;
modules.z = 0;
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:
(function() {
var x, y, z;
// variables x, y and z are available to any code inside this immediately invoked function
// and they act like global variables inside this function block and
// there values will persist for the lifetime of the program
// But, they are not truly global and will not interfere with any other global
// variables and cannot be accessed by code outside this block.
// They create both privacy and isolation, yet work just as well
})();
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:
(function(exports) {
// Creates a local symbol in this function block called exports
// that is assigned an initial value of module
})(module);
Upvotes: 25
Reputation: 664434
"self-executing" might be misleading. It is an anonymous function expression, that is not assigned or or given as an argument to something, but that called. Read here on Immediately-Invoked Function Expression (IIFE).
what is var module = {} doing?
It initializes an empty object that is acting as a namespace.
why is it called again inside the fist function?
It is not "called", and not "inside" the first function. The object is given as an argument ("exports") to the IEFE, and inside there is a property assigned to it.
Upvotes: 0
Reputation: 9530
The IIFE is adding a method to the module
object that is being passed in as a parameter. The code is demonstrating that functions create scope. Methods with the same name are being added to a object and the the head object (window) of the browser.
Upvotes: 0
Reputation: 700302
This creates a new empty object:
var module = {};
It does the same as:
var module = new Object();
This wrapper:
(function(exports){
...
}(module));
only accomplishes to add an alias for the variable module
inside the function. As there is no local variables or functions inside that anonymous function, you could do the same without it:
module.notGlobalFunction = function() {
console.log('I am not global');
};
An anonymous function like that could for example be used to create a private variable:
(function(exports){
var s = 'I am not global';
exports.notGlobalFunction = function() {
console.log(s);
};
}(module));
Now the method notGlobalFunction
added to the module
object can access the variable s
, but no other code can reach it.
Upvotes: 2