samedi 2 décembre 2017

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 is using either of them?
  2. Should one of these patterns be avoided?
  3. Is there a better way to use either of them?

Aucun commentaire:

Enregistrer un commentaire