I'm reading the book Learning JavaScript Design Patterns recently. What I don't get is the difference between module pattern and revealing module pattern. I feel they are the same thing. Anyone can give an example?
There are at least three different ways to implement the Module Pattern, but the Revealing Module Pattern is the only Module Pattern descendant that has an official name.
The Basic Module Pattern
The Module Pattern must satisfy the following:
- Private members live in the closure.
- Public members are exposed in the return object.
But there's a lot of ambiguity in this definition. By resolving the ambiguity differently, you get variants of the Module Pattern.
The Revealing Module Pattern
The Revealing Module Pattern is the most famous and most popular of the Module Pattern variants. It has a number of advantages over the other alternatives, such as
- Rename public functions without changing function body.
- Change members from public to private or vice versa by modifying a single line, without changing the function body.
The RMP satisfies three additional conditions in addition to those in the original:
- All members, whether public or private, are defined in the closure.
- The return object is an object literal with no function definitions. All right hand side expressions are closure variables
- All references are via the closure variables, not the return object.
The following example shows how it's used
var welcomeModule = (function(){
var name = "John";
var hello = function(){ console.log("Hello, " + name + "!");}
var welcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
return {
name: name,
sayHello: hello,
sayWelcome: welcome
}
})();
If you wanted to make name
and sayHello
private, you just need to comment out the appropriate lines in the return object.
var welcomeModule = (function(){
var name = "John";
var hello = function(){ console.log("Hello, " + name + "!");}
var welcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
return {
//name: name,
//sayHello: hello,
sayWelcome: welcome
}
})();
The Module Pattern with Object Literal
This is probably the oldest variant of the Module Pattern. Unlike RMP, there's no sexy official name for this variant.
It satisfies the following conditions, in addition to the original:
- Private members are defined in the closure.
- Public members are defined in the return object literal.
- References to public members are via
this
, whenever possible.
In the following example, you can see how, in contrast to RMP, the function definitions are actually in the return object literal, and references to members are qualified by this
.
var welcomeModule = (function(){
return {
name: "John",
sayHello: function(){ console.log("Hello, " + this.name + "!");}
sayWelcome: function() { console.log( this.hello() + " Welcome to StackOverflow!");}
}
})();
Note that unlike RMP, in order to make name
and sayHello
private, the references pointing to name
and sayHello
in the various function body definitions also have to be changed.
var welcomeModule = (function(){
var name = "John";
var sayHello = function(){ console.log("Hello, " + name + "!");};
return {
//name: "John",
//sayHello: function(){ console.log("Hello, " + this.name + "!");}
sayWelcome: function() { console.log( hello() + " Welcome to StackOverflow!");}
}
})();
The Module Pattern with Return Object Stub
This variant also has no official name.
It satisfies the following conditions, in addition to the original:
- An empty return object stub is defined at the beginning.
- Private members are defined in the closure.
- Public members are defined as members of the stub
- References to public members are via the stub object
Using our old example, you can see that public members are directly added to the stub object.
var welcomeModule = (function(){
var stub = {};
stub.name = "John";
stub.sayHello = function(){ console.log("Hello, " + stub.name + "!");}
stub.sayWelcome = function() { console.log( stub.hello() + " Welcome to StackOverflow!");}
return stub;
})();
If you want to make name
and sayHello
private as before, the references to the now-private members have to be changed.
var welcomeModule = (function(){
var stub = {};
var name = "John";
var sayHello = function(){ console.log("Hello, " + name + "!");}
stub.sayWelcome = function() { console.log( hello() + " Welcome to StackOverflow!");}
return stub;
})();
Summary
The differences between the Revealing Module Pattern and the other variants of the Module Pattern is primarily in how public members are referenced. As a result, RMP is much easier to use and modify, which accounts for its popularity. However, these advantages come at a great cost (in my opinion), which Addy Osmani alludes to in his post on the Revealing Module Pattern,
A disadvantage of this pattern is that if a private function refers to a public function, that public function can't be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions.
Public object members which refer to private variables are also subject to the no-patch rule notes above.
As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.
welcomeModule.name = 'James';
, console.log(welcomeModule.name)
would return "James", but welcomeModule.sayHello()
would output "Hello, John". But if I would expose a public method like setName = function(newName){ name = newName; }
and change the name with that, I'd get still "John" with consule.log(welcomeModule.name)
, even though welcomeModule.sayHello();
would output the new changed name. How does that work exactly? jsfiddle.net/isaacalves/brug6bsu/3 –
Poetize Object.freeze()
the published interface, so they are immutable. –
Haymaker Short answer, In Module pattern we define functions in returning object.
In Revealing Module pattern, we define functions in closure area and only use variable names in returning object.
Doing this simplifies the code and has lot of other advantages
Just try to do something based on top comment answer. May be it is safer if call private function by passing this to it, so private function could reference public function with this variable.
I created a revealing module pattern with following code.
var HTMLChanger = (function () {
var privateFunc = function () {
this.sayHello();
}
var hello = function () {
console.log('say Hello');
}
var callPrivate = function () {
privateFunc.call(this);
}
return {
sayHello: hello,
callPrivate: callPrivate
};
})();
HTMLChanger.callPrivate();
//say Hello
HTMLChanger.sayHello = function() { console.log('say Hi!') };
HTMLChanger.callPrivate();
//say Hi!
As you can see we can override public member.
Both the Module Design Pattern and the Revealing Module Design Pattern are ways of structuring JavaScript code to encapsulate and organize functionality. They both aim to achieve better modularization and encapsulation, making code easier to manage, understand, and maintain. However, they have some differences in terms of how they expose and organize their methods and properties.
Module Design Pattern: The Module Design Pattern involves creating an anonymous function that encapsulates private data and methods within a closure. This creates a private scope where variables and functions are hidden from the global scope. This pattern often returns an object containing methods and properties that can be accessed from the outside, effectively acting as a public API for the module. Here's a basic example:
const Module = (function() {
// Private variables and functions
let privateVar = 10;
function privateFunction() {
console.log("Private function called");
}
// Public API
return {
publicVar: 20,
publicFunction: function() {
console.log("Public function called");
}
};
})();
console.log(Module.publicVar); // 20
Module.publicFunction(); // "Public function called"
Revealing Module Design Pattern: The Revealing Module Design Pattern is a variation of the Module Design Pattern. Instead of returning an object containing the public API, it maps private functions and properties to a public API within the closure, effectively revealing only the parts you want to make public. This can make the code cleaner and more self-documenting by showing the structure of the public methods more explicitly. Here's an example:
const RevealingModule = (function() {
let privateVar = 10;
function privateFunction() {
console.log("Private function called");
}
function publicFunction() {
console.log("Public function called");
}
// Reveal only the public parts
return {
publicVar: privateVar,
publicFunction: publicFunction
};
})();
console.log(RevealingModule.publicVar); // 10
RevealingModule.publicFunction(); // "Public function called"
In summary, while both patterns share the concept of encapsulation and module organization, the Revealing Module Design Pattern places a stronger emphasis on clearly revealing the public API by explicitly listing the public functions and variables, making it easier to see which parts are meant to be used externally. The choice between the two patterns depends on your preference and the specific needs of your project.
© 2022 - 2024 — McMap. All rights reserved.