"Oftentimes, you do not need a factory to produce multiple objects - instead, you are…
- User
"Oftentimes, you do not need a factory to produce multiple objects - instead, you are using it to wrap sections of code together, hiding the variables and functions that you do not need elsewhere as private. This is easily achievable by wrapping your factory function in parentheses and immediately calling (invoking) it. This immediate function call is commonly referred to as an Immediately Invoked Function Expression (duh) or IIFE in short. This pattern of wrapping a factory function inside an IIFE is called the module pattern.
const calculator = (function () { const add = (a, b) => a + b; const sub = (a, b) => a - b; const mul = (a, b) => a * b; const div = (a, b) => a / b; return { add, sub, mul, div }; })();
calculator.add(3,5); // 8 calculator.sub(6,2); // 4 calculator.mul(14,5534); // 77476 In this example, we have a factory function creating some basic operations that we need only once. We can wrap it in parentheses and immediately call it by adding () - returning the result object that we store in calculator. In this way we can write code, wrapping away things that we do not need as private variables and functions inside our factory function and while they are tucked inside of our module, we can use the returned variables and functions outside the factory, as necessary.
Encapsulating with the module pattern At first glance, this does not seem particularly useful. If we have some code that we use only once, why not write it in the main section of our JavaScript file itself? After all, the power of factory functions lies in being, well, a factory to make multiple objects, right?
This is where we encounter the word encapsulation - bundling data, code, or something into a single unit, with selective access to the things inside that unit itself. While it sounds general, this is what happens when we wrap, or encapsulate our code into modules - we don’t expose everything to the body of our program itself. This encapsulation leads to an effect called namespacing. Namespacing is a technique that is used to avoid naming collisions in our programs.
Take the calculator example into consideration. It’s very easy to imagine a scenario where you can accidentally create multiple functions with the name add. What does add do - does it add two numbers? Strings? Does it take its input directly from the DOM and display the result? What would you name the functions that do these things? Instead, we can easily encapsulate them inside a module called calculator which generates an object with that name, allowing us to explicitly call calculator.add(a, b) or calculator.sub(a, b)."
Isso é de um artigo do Odin Project. Eu quero entender do porque que eu precisaria usar um IIFE com um factory function dentro, sendo que é só criar um objeto e definir suas funções pra cada propriedade do objeto? Porque do jeito que o exemplo mostrou, eu não entendo o que exatamente ele "priva".
- Assistant
In the example you provided from The Odin Project, the key concept being demonstrated is encapsulation through the use of the module pattern and Immediately Invoked Function Expressions (IIFEs) in JavaScript. I understand your confusion—on the surface, it might seem unnecessary to wrap the factory function in an IIFE when you could just create an object with methods. Let's delve deeper to clarify what's happening and why this pattern is beneficial.
What's Being "Privatized"?
In the example:
const calculator = (function () { const add = (a, b) => a + b; const sub = (a, b) => a - b; const mul = (a, b) => a * b; const div = (a, b) => a / b; return { add, sub, mul, div }; })();The functions
add,sub,mul, anddivare defined within the scope of the IIFE. This means they are not accessible from the global scope or anywhere outside the IIFE. When you return{ add, sub, mul, div }, you're creating an object with references to these functions, but the functions themselves remain scoped within the IIFE.This pattern allows you to:
- Encapsulate the functions and any variables you might have inside the module.
- Expose only what you need by returning an object with selected properties.
- Prevent naming collisions by not polluting the global namespace with function names like
add,sub, etc.
Why Not Just Create an Object with Methods Directly?
If you were to create an object directly, like this:
const calculator = { add: (a, b) => a + b, sub: (a, b) => a - b, mul: (a, b) => a * b, div: (a, b) => a / b };You're defining the methods directly on the
calculatorobject. While this works and the methods are accessible viacalculator.add, etc., there's no scope encapsulation. If you had helper functions or variables that you didn't want exposed, you wouldn't be able to hide them easily using this approach.The Benefits of Using an IIFE with the Module Pattern
-
Encapsulation and Privacy
By using an IIFE, you're creating a new scope that is not accessible from the outside. Any variables or functions defined inside this scope are effectively private. This allows you to hide implementation details and expose only what's necessary.
const calculator = (function () { const version = '1.0'; // private variable const add = (a, b) => a + b; // Only exposing the add function return { add }; })(); console.log(calculator.version); // undefinedIn this example,
versionis not accessible outside the IIFE. If you had used a plain object,versionwould either have to be exposed or not usable. -
Avoiding Naming Collisions
In larger applications or when integrating multiple scripts, function names like
addorsubmight already exist. By encapsulating them within the IIFE and exposing them through a namespace (thecalculatorobject), you reduce the risk of naming collisions. -
Controlled Access to Module Contents
The module pattern allows you to expose only the parts of your code that other parts of your application need to use. This leads to a cleaner and more maintainable codebase.
-
Ability to Maintain State Privately
You can have private variables that maintain state between method calls without exposing or altering the global scope.
const counterModule = (function () { let count = 0; // private variable const increment = () => ++count; const decrement = () => --count; const getCount = () => count; return { increment, decrement, getCount }; })(); counterModule.increment(); counterModule.increment(); console.log(counterModule.getCount()); // 2 console.log(counterModule.count); // undefinedHere,
countis a private variable. There's no way to directly modify it from outside the module except through the exposed methods.
Understanding the Need for the IIFE in the Module Pattern
The IIFE serves to create a private scope. Without it, all variables and functions defined would be in the global scope (or the surrounding scope in a module system), potentially leading to conflicts and unintended side effects.
Consider another example without an IIFE:
const version = '1.0'; const add = (a, b) => a + b; // ...Now,
versionandaddare in the global scope (assuming you're not in a module), which can cause problems.Summary
- IIFE creates a private scope: Variables and functions inside are not accessible from outside unless explicitly exposed.
- Encapsulation: You can hide implementation details and only expose a public interface.
- Avoids global namespace pollution: Reduces the risk of naming conflicts.
When Is This Pattern Particularly Useful?
- Complex Modules: When your module has internal helper functions or variables that you don't want exposed.
- Stateful Modules: When you need to maintain internal state between method calls.
- Large Applications: To prevent naming collisions and manage code organization.
A More Elaborate Example
To illustrate the benefits, let's extend the calculator example:
const calculator = (function () { const history = []; // private variable to store operation history function log(operation, a, b, result) { history.push({ operation, a, b, result }); } const add = (a, b) => { const result = a + b; log('add', a, b, result); return result; }; const sub = (a, b) => { const result = a - b; log('sub', a, b, result); return result; }; const getHistory = () => history.slice(); // expose a copy of history return { add, sub, getHistory }; })(); calculator.add(5, 3); // 8 calculator.sub(10, 4); // 6 console.log(calculator.getHistory()); // [ { operation: 'add', a: 5, b: 3, result: 8 }, // { operation: 'sub', a: 10, b: 4, result: 6 } ] console.log(calculator.history); // undefinedIn this example:
historyandlogare private: They can't be accessed or modified directly from outside the module.- State Management: The module maintains state (
history) across method calls. - Controlled Exposure: Only
add,sub, andgetHistoryare exposed.
Conclusion
Using an IIFE with a factory function inside allows you to leverage the module pattern's full power—encapsulation, privacy, and controlled exposure of your module's interface. While for simple cases it might seem like extra work, this pattern scales well for more complex modules where you need to protect internal variables and functions from external access and modification.
I hope this clarifies why the IIFE is used in conjunction with the factory function in the module pattern and what exactly it "privatizes." It's less about the immediate need in a simple example and more about demonstrating a robust pattern for organizing and protecting your code in larger applications.