CS_2013 CS_2013 - 1 month ago 12
Javascript Question

Why does module pattern create a singleton?

When I try and make different instances of this module, it does not work.

It seems to be a singleton. I can only have one instance at a time.

What mechanism limits the constructor function publik() to only have on instance?

http://jsfiddle.net/AVxZR/

var Module = ( function ()
{
var publik = function ( )
{
};
publik.prototype.test;
publik.prototype.get = function()
{
document.getElementById( 'a'+test ).innerHTML = test;
};
publik.prototype.set = function( value )
{
test = value;
};
return publik;
} ) ();

var object1 = new Module();
var object2 = new Module();

object1.set('1');
object2.set('2');


object1.get();
object2.get();

Answer

The short answer: closure.

The long answer (if I have it right, please comment so I can correct):

  1. Your Module var is a executed immediately when the script loads. (denoted by the parenthesis around the function.)()

  2. In that module, your publik var is declared and it's left in the closure even when the function completes!

  3. With subsequent calls, you still access that one Module that was auto-executed. And it always gets that same closure space and function scope and the same object, in short - so your publik variable is actually always the same one.