Search code examples
javascriptrevealing-module-pattern

Difference between Revealing Module Pattern and simple Constructor


Googled but did not find appropriate resource to explain the difference between using Revealing Module Pattern and this keyword.

When using revealing module pattern I can have the below code :

var moduleRevealing = function() {
    var talk = function() {
      console.log("Talking....");
    };
    var walk = function() {
      console.log("Walking...");
    };
    return {
      talk: talk,
      walk: walk
    }
  };

  console.log('Module Pattern Object');
  console.log(moduleRevealing());

Now the same thing can be achieved using this keyword as below:

var module = function() {
    var talk = function() {
      console.log("Talking....");
    };
    this.walk = function() {
      console.log("Walking...");
    };
    this.talk = talk;
  };
  var mod1 = new module();
  console.log('Module Object');
  console.log(mod1);

How are both different? I can only see one difference and that is the __proto; The former points to Object while the later is module.

In case someone want's to see the code - Fiddle


Solution

  • In your simple example there is no difference, but let me make it just a little more complicated.

    var moduleRevealing = function() {
        var talk = function() {
          console.log("Talking....");
        };
        var walk = function() {
          console.log("Walking...");
        };
        var walkAndTalk = function(){
          walk();
          talk();
        };
        return {
          talk: talk,
          walk: walk,
          walkAndTalk: walkAndTalk
        }
      };

    Using this,

    var module = function() {
        var talk = function() {
          console.log("Talking....");
        };
        this.walk = function() {
          console.log("Walking...");
        };
        this.talk = talk;
        this.walkAndTalk = function(){
          this.walk();
          this.talk();
        }
      };

    These two slightly more complicated examples now have very different behavior when you override their methods.

    var modR = moduleRevealing();
    var mod1 = new module();
    modR.walk = function() {console.log('FAST Walking...");}
    mod1.walk = function() {console.log('FAST Walking...");}
    
    modR.walk(); // outputs "FAST Walking..."
    modl.walk(); // outputs "FAST Walking..."
    
    modR.walkAndTalk(); // outputs "Walking ... Talking..."
    mod1.walkAndTalk(); // outputs "FAST Walking...Talking..."

    Note that even though walk()'s output is changed When you override an instance created using Revealing Module, that change isn't picked up by the dependent method walkAndTalk(). The underlying reason is that the Revealing Module pattern encourages the indiscriminate use of javaScript closures for people who haven't bothered to learn this properly. See this post of mine for a comparison of difference between module pattern variants.