How to use Revealing module pattern in JavaScript
Asked Answered
M

10

78

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?

Marje answered 13/4, 2011 at 9:46 Comment(2)
For me this article is the best explanation I've seen so far.Gaynellegayner
Why use the Revealing Module Pattern, when you can use the Definitive Module Pattern? github.com/tfmontague/definitive-module-patternEnceinte
K
99

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)
Kal answered 13/4, 2011 at 10:0 Comment(6)
this pattern changed my life!Capital
I know this is old, but the return value of abc() is missing a parenthesis =]Weighbridge
Why use the Revealing Module Pattern, when you can use the Definitive Module Pattern? github.com/tfmontague/definitive-module-patternEnceinte
How do I create a new instance of revealed?Honeycutt
@NeonWarge: you don't. The function is not a constructor. It returns an object literal, in which a and abc are closed over.Kal
@NeonWarge: although you probably no longer have this question, if you remove the last ()'s then you can just call revealed as many times as you want to create new objects of this type.Gonroff
M
23

DC = Douglas Crockford
RMP = Revealing Module Pattern

Difference between DC and RMP is mainly organizational/readable

Example is presented in the article itself? And what exactly are you asking because those things don't have anything to do with files but rather to closures.

You put everything in a closure (function) and expose only those part that you wish to be accessible. The difference between DC style and RMP is that in the first one functions are defined in different places while in the RMP they're always defined in the same place and then afterwards revealed in the public object literal.

So in the DC and RMP you have:

  • closure that makes it possible to define private parts (variables and functions)
  • private part
  • public result that defines publicly visible functionality and variables (state)

These two patterns differ only in readability. In DC case you can't always know where certain functionality will be defined, but in the RMP you always know everything is in the private part.

Metachromatism answered 13/4, 2011 at 9:55 Comment(1)
It's not true that DC and RMP are the same -- the two are very different when it comes to inheritance. See #21926220 for instanceNolasco
S
13

Revealing module pattern is described pretty good in Essential JavaScript Design Patterns For Beginners article.

Separator answered 13/4, 2011 at 9:53 Comment(0)
F
6

The method called by the author "Douglas Crockford's pattern for creating objects" is actually the module pattern that was developed mostly by Richard Cornford et al. See http://groups.google.com/group/comp.lang.javascript/msg/9f58bd11bd67d937

As for examples, there are many. Read the following article and follow some of the links: http://peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in-javascript-tm

Frankfurter answered 13/4, 2011 at 10:1 Comment(2)
I redid my post, please let me know if there are still any issues :)Viburnum
Interesting how these things morph over time. The "revealing" version has been used by David Mark (of MyLibrary fame) for some time, I have no issues with the "non—revealing" version so I use that. :-)Frankfurter
L
1

I like to use a mixture of the revealing module pattern with the singleton pattern so that I can keep structured code with the benefits of the module pattern:

var MyFunction = function(){

    var _ = {
       Init: function(){
          _.Config.foo = "hello world";
       },
       Config:{
          foo:null
       },
       ShowAlert:function(){
          alert(_.Config.foo);
       }
    }

    return {
        Init: _.Init,
        ShowAlert: _.ShowAlert
    };
}();

MyFunction.Init();
MyFunction.ShowAlert();

I've wrote more information on this on my blog:

http://curtistimson.co.uk/js/mixing-revealing-module-and-singleton-javascript-patterns/

Lashio answered 22/6, 2015 at 12:30 Comment(0)
G
1

Just want to add: with this pattern it's good to pass global dependencies as arguments/params so that they are explicit. You don't have to do it but this makes it very clear what your module needs from the first glance. E.g.:

var myModule = (function ($, loadModule) {
  "use strict";
})(jQuery, load);

In this example, you can see right away in the 1st line that you module uses jQuery and some other module responsible for loading functionality.

Guarantor answered 16/10, 2018 at 17:31 Comment(0)
O
0

To the code outside the module, it makes little difference. In all 3 cases in that article, the methods are called the same way. But the structure of the module itself is internally different.

Crockford's module pattern and what they call the "revealing module pattern" are pretty much the same thing, structurally. The only difference being that they assign the method to a local var first in order be more readable. But there really isn't anything special about it, and you have some examples right there in your link.

Ostracism answered 13/4, 2011 at 9:54 Comment(1)
The object returned by the revealing module pattern does not behave like Douglas Crockford's module pattern with respect to overriding (see Addy Osmani's warning at addyosmani.com/resources/essentialjsdesignpatterns/book/…).Nolasco
B
0

The basic concept of a Revealing Module is that you have an Object which encapsulates its data and behavior:

var Module = (function(){
    var privateStuff = {};
    var publicStuff = {};

    return publicStuff;
})();

However, there are some best practices you should employ when using this pattern. Here's a module ("Modulus") with some properties for demonstration sake, which employs some of these practices:

function AbstractSomeClass(id) {
    this.id = id;
    return this;
}

var Modulus = (new (function SomeClass() {
    var thus = this;

    function NameClass(name){
        this.value = thus.name || name;
    }

    AbstractSomeClass.call(this, 998);

    this.name = 'Touring';
    this.name = ( new NameClass('Hofstadter') ).value;

    return {
        id: this.id,
        name: this.name
    };
})());

Notice the (new (function SomeClass(){ ... })()); syntax. Using new like this allows you to use the this keyword inside of the closure. This is handy if you need to inherit properties from another class (AbstractSomeClass.call(this, 998);) -- However, you'll still need to reveal the properties that you would like to have public, e.g.:

return {
    id: this.id,
    name: this.name
};

Also notice that we assign this to thus -- which allows us to use the Parent-this inside of a subclass that has its own this scope (this.value = thus.name || name;)

Once again, these are just a few of the conventions and best practices that are suggested.

Broider answered 15/8, 2014 at 20:49 Comment(0)
G
0

Here is the small example of revealing module pattern.

It provides a facility to declare private and public functions just like a class.It is the major benefits of this patterns.If we do not want to expose some of the functionality accessible from globally then makes it private and rest of the make public.Below is the example how to make private and public functions.And one more things it is a self-executable block of code.

  var Calculator = (function () {

        var num1 = 10;
        var num2=5
        var _abc = function () {
            return num1 - num2;
        };

        var _mulFunc = function () {
            return num1 * num2;
        };

        var _divFunc = function () {
            return num1/num2;
        };

        return {
           //public scope
            abc: _abc,
            mulFunc:_mulFunc
         };

    })();

alert(Calculator.abc()); it returns 5

alert(Calculator.mulFunc()); it returns 50

And __divFunc() will not be accessible as it is in private scope. We can access only those functions which is declared inside return object as it is public function representation

Groningen answered 24/9, 2017 at 17:50 Comment(0)
B
0

https://tarunnagpal78.medium.com/revealing-module-design-pattern-in-javascript-3b0db0bcd121

I have written an article on it.

You can have a look at this

Binah answered 25/6, 2020 at 17:49 Comment(2)
Your link is brokenCapital
Thanks, @Capital for pointing this out. I have updated the link tarunnagpal78.medium.com/…Binah

© 2022 - 2024 — McMap. All rights reserved.