Reputation: 2425
I struggle to understand the advantages of the revealing module pattern. Take f.e. the following code:
var Person = function(name){
this.name = name;
var priv = 'secret';
}
var OtherPerson = function(name){
var name = name;
var priv = 'secret';
return({name: name});
}
duke = new Person('john');
dust = new OtherPerson('doe');
To my knowledge OtherPerson should be a classic revealing module as I found it in various resources in the web. So what is the difference between Person and OtherPerson?
I personally think that Person looks a lot cleaner and you can see your private and public variables more easily.
Upvotes: 2
Views: 246
Reputation: 11586
Well,
duke
is a Person
dust
is not an OtherPerson
In JavaScript:
instanceof duke === Person // true
instanceof dust !== AnotherPerson // true
The Person
pattern might be useful for building an object that will be instantiated, and that can also be a module. The OtherPerson
constructor, on the other hand, only returns a simple JavaScript object, so there is no sense to instantiate it later. Yet, a module that is not an object constructor can use this pattern (for example, a function that uses other locally defined data).
Upvotes: 3
Reputation: 3248
The Module Pattern gives you the advantage of being able to hide your private variables and methods. The Revealing Module Pattern variant implementation gives you the ability to easily modify your code to switch from private to public and vice versa, but at a significant cost. See this answer for the differences in Module Pattern implementations, but the gist of it is that the Revealing Module Pattern behaves poorly with respect to overriding and prototypal inheritance.
Your OtherPerson
is an example of the Revealing Module Pattern. Your Person
is classic JavaScript, though, depending on how you implement a more complicated example, it can be used like the original implementation of the Module Pattern with respect to regular overriding and prototype overriding. Where the Module Pattern differs from your example is that the Module Pattern avoids the use of the new
keyword which many people loathe, and that the Module Pattern organization makes it easier to see which methods are public vs. which are are private.
Upvotes: 0