var LazySingleton = function(){
var val = 1, _instance;
var lazy_init = function(){
alert('Lazy init, exec no more than once.');
return {
getVal : function(){ return val; },
setVal : function(v){ val = v; }
};
};
var init = function(){
init = function(){ return _instance; };
return _instance = lazy_init();
};
return {
getInstance : function(){ return init(); }
};
}();
alert('load before lazy init.');
var ls1 = LazySingleton.getInstance(); // will exec lazy init
alert(ls1.getVal()); // 1
ls1.setVal(5);
var ls2 = LazySingleton.getInstance(); // won't exec lazy init
alert(ls2.getVal()); // 5
alert(ls1 == ls2); // true
alert(ls1 === ls2); // true
点击这里在线测试