KingKongFrog
KingKongFrog

Reputation: 14419

Javascript - Module Pattern differences

Is there any difference b/w the following 2 patterns? What is the advantage of self-executing the first one?

var testModule = (function () {
  var counter = 0;

  return {
    incrementCounter: function () {
      return counter++;
    },

    resetCounter: function () {
      console.log( "counter value prior to reset: " + counter );
      counter = 0;
    }
  };
})();

testModule.incrementCounter(); // 1

Next:

var testModule2 = function () {
  var counter = 0;

  return {
    incrementCounter: function () {
      return counter++;
    },

    resetCounter: function () {
      console.log( "counter value prior to reset: " + counter );
      counter = 0;
    }
  }
}

var result = testModule2();
result.incrementCounter(); //1

Upvotes: 1

Views: 38

Answers (1)

raina77ow
raina77ow

Reputation: 106385

The first one is a singleton - you can clone it, of course, but it'll be quite awkward, first, and won't make copies of that private variables: all the methods of all the cloned objects will still work with the same var counter. That's why it's suitable for making service-like things.

The second one is a variant of constructor function actually - and it's suitable for creating multiple things based on a single template. Its drawback (comparing with classical prototype-based templates) is that all the functions defined in it will be created anew each time a testModule2 is invoked. Its advantage - private variables, an independent set for each new object (note the difference with cloning the objects created with the first approach).

Upvotes: 4

Related Questions