1

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
3
  • 2
    The most obvious difference is that the first can create only one object, while the second can create multiple. Were you looking for something beyond that? Commented Mar 31, 2014 at 16:32
  • Ahhh I see. I didn't notice that. So the first one would allow only one object and the second I can contain multiple? Commented Mar 31, 2014 at 16:34
  • 1
    Well, when you keep a reference to a function, you can invoke it as many times as you want. If you keep no reference, but instead only invoke it immediately, it's useful only that one time. This has nothing to do with the module pattern. It's just simple logic. You can't invoke a function that you can't reference. Commented Mar 31, 2014 at 16:36

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.