Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 456
CS_2013 Avatar asked May 21 '12 19:05

CS_2013


People also ask

Why are singleton objects created?

The primary purpose of a Singleton class is to restrict the limit of the number of object creation to only one. This often ensures that there is access control to resources, for example, socket or database connection.

Are Javascript modules singletons?

The ES6 Way — modulesES6 Modules are singletons. Thus all you have to do is define your object in a module. To test, you can try: const phrase = `${Math.

Why we are using singleton pattern?

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.

What are Python singletons?

A Singleton pattern in python is a design pattern that allows you to create just one instance of a class, throughout the lifetime of a program. Using a singleton pattern has many benefits. A few of them are: To limit concurrent access to a shared resource. To create a global point of access for a resource.


2 Answers

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.

like image 72
Zlatko Avatar answered Sep 23 '22 18:09

Zlatko


You code doesn't create a singleton. It only acts like a singleton since your test variable is a global variable.

To fix this change test to this.test so the variable is attached to each instance.

like image 37
Brian Avatar answered Sep 23 '22 18:09

Brian