What is the simplest/cleanest way to implement singleton pattern in JavaScript?
+22
A:
I think the easiest way is to declare a simple object literal:
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() {
var privateVar = '';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// all private members are accesible here
},
publicMethod2: function () {
}
};
})();
This is has been called the module pattern, it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
CMS
2009-09-25 20:10:02
+1 Nicely done.
Andrew Hare
2009-09-25 20:10:33
Thanks @Andrew!
CMS
2009-09-25 20:45:39
+1 Isn't it a bit strange to look for a "Singleton pattern" in a language with global variables???
Victor
2009-10-28 09:18:22
+1
A:
How about this, the variable called 'hidden' is private and cannot be replaced because it is hidden within a closure.
var singleton = {
// private object
var hidden = { id = 5 }; // wherever you want
return {
getInstance: function() { return hidden; }
};
}();
BeWarned
2009-09-25 20:14:13