What is the simplest/cleanest way to implement singleton pattern in JavaScript?
Module pattern: in "more readable style". You can see easily which methods are publics and which ones are privates
var module = (function(_name){
/*Local Methods & Values*/
var _local = {
name : _name,
flags : {
init : false
}
}
function init(){
_local.flags.init = true;
}
function imaprivatemethod(){
alert("hi im a private method");
}
/*Public Methods & variables*/
var $r = {}; //this object will hold all public methods.
$r.methdo1 = function(){
console.log("method1 call it");
}
$r.method2 = function(){
imaprivatemethod(); //calling private method
}
$r.init = function(){
inti(); //making init public in case you want to init manually and not automatically
}
init(); //automatically calling init method
return $r; //returning all publics methods
})("module");
now you can use publics methods like
module.method2(); //-> I'm calling a private method over a public method alert("hi im a private method")
http://jsfiddle.net/ncubica/xMwS9/