What is the simplest/cleanest way to implement singleton pattern in JavaScript?
There is more than one ways to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for CMS' first solution whenever possible (when you don't need privacy). Since the question was about the simplest and cleanest, that's the winner. Or even:
var myInstance = {}; // done!
This (quote from my blog) ...
var SingletonClass = new function() {
this.myFunction() {
//do stuff
}
this.instance = 1;
}
doesn't make much sense (my blog example doesn't either) because it doesn't need any private vars, so it's pretty much the same as:
var SingletonClass = {
myFunction: function () {
//do stuff
},
instance: 1
}