Friday, November 5, 2010

Javascript Singleton Object

Have you come across a problem where you have to create an object that can only be initialized once and you want to reuse that object throughout your whole application? Well maybe you haven't but I actually came across that problem the other day and here's the solution for it:

function singleton() {
var instance = (function() {
var privateVar;

function privateMethod () {
// ...
}

return { // public interface
publicMethod1
: function () {
// private members can be accessed here
},
publicMethod2
: function () {
// ...
}
};
})();

singleton
= function () { // re-define the function for subsequent calls
return instance;
};

return singleton(); // call the new function
}
Solution given by CMS on Stack overflow(http://stackoverflow.com/questions/1895635/javascript-singleton-question)

No comments: