mercredi 29 juin 2016

Singleton design pattern in Javascript

I am following this link http://ift.tt/1UyR1QI 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.

Aucun commentaire:

Enregistrer un commentaire