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
-
2The 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?cookie monster– cookie monster2014年03月31日 16:32:34 +00:00Commented 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?KingKongFrog– KingKongFrog2014年03月31日 16:34:34 +00:00Commented Mar 31, 2014 at 16:34
-
1Well, 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.cookie monster– cookie monster2014年03月31日 16:36:59 +00:00Commented Mar 31, 2014 at 16:36
1 Answer 1
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).