IMPROVISING MODULE SYSTEMS
In order to offer the encapsulation required by the module pattern, pre-ES6 modules sometimes used function scope and immediately invoked function expressions (IIFEs) to wrap the module definition in an anonymous closure. The module definition is executed immediately, as shown here:
(function() {
// private Foo module code
console.log('bar');
})();
// 'bar'
When the return value of this module was assigned to a variable, this effectively created a namespace for the module:
var Foo = (function() {
console.log('bar');
})();
'bar'
In order to expose a public API, the module IIFE would return an object whose properties would be the public members inside the module namespace:
var Foo = (function() {
return {
bar: 'baz',
baz: function() {
console.log(this.bar);
}
};
})();
console.log(Foo.bar); // 'baz'
Foo.baz(); // 'baz'
A similar pattern to the previous one, termed the...