What is the simplest/cleanest way to implement singleton pattern in JavaScript?
Function - SimplestCleanest way to implement singleton in JavaScript
De openkb
Sommaire |
Questions
Answers
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 () {
}
};
})();
http://www.jibbering.com/faq/faq_notes/closures.html http://www.jibbering.com/faq/faq_notes/closures.html
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript