代码改变世界

JavaScript Lazy单件 - 延迟到第一次访问才执行构造函数

2011-04-07 17:41  JimLiu  阅读(627)  评论(0编辑  收藏  举报
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
点击这里在线测试