The central principle of the Revealing Module pattern is that all functionality and variables should be hidden unless deliberately exposed.
Let’s imagine we have a music application where a musicPlayer.js file handles much of our user’s experience. We need to access some methods, but shouldn’t be able to mess with other methods or variables.
Using Function Scope to Create Public and Private Methods
We can move all functionality inside a function’s scope. Then we return an object with the functions that we’d like accessible in other files.
Now we can access all the methods that we need on our
musicModule object. But we can't fiddle with our
songList or access the
loadSong() method. These are both private.
This works fine. But there’s one big problem.
musicPlayer as a namespace to hold our functions. But wait, our
musicPlayer is a function that's still exposed to the global scope!
Someone could come along and invoke it again, creating a new
musicPlayer. Then we would have multiple instances of
musicPlayer floating around, polluting our environment and causing all sorts of confusion.
Hiding Your Module with an IIFE
The best way to avoid exposing your top-level function to the global scope is to wrap everything in an IFFE. An IIFE is an immediately-invoked function expression. That’s a mouthful. It just means that we call (invoke) this function as soon as the file is run (immediately).
Since our function has no name, we call it an expression. Since it has no name, it can never be invoked elsewhere.
Here’s how that looks:
Our function-level scope still keeps our methods and variables public and private based on whether we expose them in the return object.
But this time, we avoid the risk that we can invoke our module elsewhere in the code.
In other files we can now use
musicModule's' functionality – a well-encapsulated module in our global scope!
Originally published at gist.github.com.