Dinesh Pandiyan
Dinesh Pandiyan

Reputation: 6289

Javascript Module Pattern - difference

I am aware of javascript module pattern but I use two types of module patterns and would like to know the difference between them from an architectural perspective.

// PATTERN ONE
var module = (function() {
  var _privateVariable = '';

  var _privateMethod = function() {
    var _this = this;
    // private method def
    // can use _this._privateVariable
    console.log('Inside a private method!');
  };

  var publicMethod = function() {
    var _this = this;
    // public method def
    // can use _this._privateVariable
    // can call _privateMethod();
  };

  return {
    publicMethod: publicMethod
  };
})();

// PATTERN TWO
var module = (function() {
  var wrapper = {
    _privateVariable: '',

    _privateMethod: function() {
      var _this = this;
      // private method def
      // can use _this._privateVariable
      console.log('Inside a private method!');
    },

    publicMethod: function() {
      var _this = this;
      // public method def
      // can use _this._privateVariable
      // can call _privateMethod();
    },
  };

  return {
    publicMethod: wrapper.publicMethod
  };
})();

Both these patterns seem to do the same thing for me

  1. Is there a significant difference in using either of them?
  2. Should one of these patterns be avoided?
  3. Is there a better way to use either of them?

Upvotes: 0

Views: 52

Answers (1)

Krishna Modi
Krishna Modi

Reputation: 397

In fact, there is no difference between the two patterns you've mentioned. Only difference I see is that the second pattern uses wrapper as an extra variable which can be avoided.

Considering other cases, where you might want to return a complex object rather than the current one, then the second pattern is very useful,

for eg.

var wrapper = {
_privateVariable: '',

_privateMethod: function() {
  var _this = this;
  console.log('Inside a private method!');
},

publicMethod: function() {
  var _this = this;
},

publicMethod2: function() {
  var _this = null;
},

publicMethod3: function(default) {
  var _this = default;
},
};

return {
   publicMethod: wrapper
};

Upvotes: 1

Related Questions