2

I am following this link https://addyosmani.com/resources/essentialjsdesignpatterns/book/ to understand design patterns in Javascript I understood constructor pattern , module pattern and module revealing pattern , now in Singleton pattern I have two doubts which are following :

1) I know c++ and I am learning JavaScript now, so I understand singleton pattern allows you only one instance of the class but in this book it's mentioned "In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions." What does it mean ???

2)

var mySingleton = (function () {

// Instance stores a reference to the Singleton
var instance;

function init() {

// Singleton

// Private methods and variables
function privateMethod(){
    console.log( "I am private" );
}

var privateVariable = "Im also private";

var privateRandomNumber = Math.random();

return {

  // Public methods and variables
  publicMethod: function () {
    console.log( "The public can see me!" );
  },

  publicProperty: "I am also public",

  getRandomNumber: function() {
    return privateRandomNumber;
  }

};

};

return {

// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {

  if ( !instance ) {
    instance = init();
  }

  return instance;
}

};

})();

var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();

My doubt is when we call mySingleton.getInstance(); won't be the value "instance" undefined again, as it is a local variable and everytime we call the getInstance method it should set the instance value as undefined and hence if ( !instance )
should pass always and give a new instance but I don'y understand how it's working here. Kindly explain.

4
  • No, var instance defined in "outer" scope. (not in scope of getInstance function) Commented Jun 30, 2016 at 5:33
  • My advice is to look up what closures are in Javascript. Commented Jun 30, 2016 at 5:49
  • Thanks point 2 is clear now... but what about point no 1 ? Kindly explain ... Commented Jun 30, 2016 at 5:57
  • @user3651606 does the book suggest that in javascript the singleton is used differently than in other languages? That text sortof just defines what a singleton is. Commented Jun 30, 2016 at 8:50

3 Answers 3

1

var mySingleton is a IIFE function and this returns you an object (or in module revealing pattern term, exposes property of getInstance)

Every time mySingleton is referred in the code, the content inside it executes every time. Hence resetting instance variable. Note, init method also returns an object with 3 properties indicating that these are exposable too (can be made public and even the private variables can be made public by processing them in a public function. Pretty much the C++/Java concepts).

In the end, we use this init() and tag it to getInstance

Hence when I do var singleA = mySingleton.getInstance(); var singleB = mySingleton.getInstance();

I can access the (selectively)"exposed" properties singleA.publicMethod()

Flow: singleA [refers to] getInstance() [exposed through] mySingleton [and] getInstance() [refers to] init() [which exposes] publicMethod, publicProperty and getRandomNumber [which indirectly gives you access to] privateRandomNumber

Doubt #1 Serve as a shared resource namespace and hide code implementation. It is sharing the private properties and methods of init method globally whilst you are in a namespace 1 level above init.

Private methods are hidden and not exposed.

Doubt #2 Every time mySingleton is referred, instance is re-declared.

Hope this helps

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

Comments

0

1) This means that only variable var mySingleton is now accessible from global namespace. It exposes single public method getInstance which returns one and only one instance of a class (code responsible for managing private reference to this instance is hidden from outside scope).

2) No, var instance is defined in "outer" scope. (not in scope of getInstance function)

Comments

0

In javascript Object is a reference data type which means the instance returned here is same.

var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();

singleA === singleB // > true

and the fact that we are able to access the instance variable in getInstance function of mySingleton is due to closure's

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.