Created
November 18, 2012 06:04
-
-
Save airyland/4103832 to your computer and use it in GitHub Desktop.
JavaScript Lazy init
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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