Singleton pattern in Javascript

If you’d like to create just one instance of a Class, you’d better use this singleton pattern:


var singleton = function() {

/ Private variables /

var privateVariable;

/ Private methods /

function privateFunction(x) {
// do something here…
}

return {

/* Public variables */

publicVariable = 15,

/* Public methods */

getVariable: function() {
  return privateVariable;
},

setVariable: function() {
  privateVariable = 18;
  privateFunction();
}

};

}();


The magic of this pattern lies in the instanciation of the singleton:

the main function is called directly due to the ‘()’ at the end.

Comments

comments powered by Disqus
Copyright © 2000-2015 - Eric Abouaf - Powered by Hexo