The 3 faces of an IIFE Module
There are 3 conventional ways to create an IIFE module. They all return the same value, but syntactically they look different. They all use closures to access private properties of the outer function.
An IIFE is an Immediately Invoked Function Expression: the outer function is wrapped in parentheses and executed by adding a trailing set of parentheses. When that function executes, it returns an object that has inner functions have can reference private properties via closures.
Convention #1: declare the functions within the returned object:
var mod = (function() {
var privateProp = ‘name’;
return {
getName : function() { return privateProp; }
};
})();
2. Convention #2: declare the functions outside the returned object, and use the returned object’s method properties to reference those inner functions:
var mode = (function() {
var privateProp = ‘name’;
function _getName() {
return privateProp;
}
return {
getName : _getName
};
})();
3. Convention #3: declare the functions outside the returned object, and create an object to assign those inner functions to the obj’s method properties:
var mod = (function() {
var privateProp = ‘name’;
var tempMod = {};
tempMod.getName = function() {
return privateProp;
}
return tempMod;
})();
These 3 ways of creating an IIFE module all create closures that returns an object whose functions can access private properties.