Skip to content

Instantly share code, notes, and snippets.

@airyland
Created November 18, 2012 06:04
Show Gist options
  • Save airyland/4103832 to your computer and use it in GitHub Desktop.
Save airyland/4103832 to your computer and use it in GitHub Desktop.
JavaScript Lazy init
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment