I stumbled across this post: JavaScript's Revealing Module Pattern. I would like to use this in my project.
Let's imagine I have a function abc
and I am calling that function in my main JavaScript file.
Does this pattern make things different? Can anyone show me a basic example of this pattern?
The biggest advantage of revealing module pattern as compared to the module pattern is the code readability aspect. The revealing module pattern is used to provide an abstraction over private implementations by providing public APIs.
The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope. It is used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function.
Revealing Module Pattern is JavaScript's design pattern that is available for users to actually organize JavaScript's codes in modules which actually gives better code structure and helps in making things either private or public to users.
A small example:
var revealed = function(){ var a = [1,2,3]; function abc(){ return (a[0]*a[1])+a[2]; } return { name: 'revealed', abcfn: abc } }();
in the anonymous function that is initiated to give revealed
a value, a
and abc
are private to that function. What the function returns is an object literal with a name
property and a abcfn
property, which is a reference to the abc function
. The abc function
uses the private variable a
. This can all be done thanks to the use of closures (everything within the scope of a function can be referenced by everything else in that same function).
Revealed usage:
alert(revealed.name); //=> 'revealed' alert(revealed.abcfn()); //=> 5 (1*2+3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With