js单例模式

<!DOCTYPE html>  
<html>  
<head>  
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>  
</head>  
<body>   
<script>  
    var Single = (function () {
        var instance = null;
        var defaultData = {age: 25};
        SingleInstance.prototype._init = function (ops) {
            for (var a in defaultData) {
                this[a] = defaultData[a];
            }
            for (var b in ops) {
                this[b] = ops[b];
            }
        };
        function SingleInstance(args) {
            if (this instanceof SingleInstance) {
                if (instance == null) {
                    instance = this;
                }
                instance._init(args);
                return instance;
            }else {
                if(instance==null){
                    instance=new SingleInstance;
                }
            instance._init(args);
                return instance;
            }
        }
        return SingleInstance;
    })();

    var i1 = new Single({name: "xu"});
    var i2 = new Single({name: "tong"});
    var i3 = Single({name: "bao"});
    console.log(i1 === i2);  //true
    console.log(i1 === i3);  //true
    console.log(i1.name);    //bao
    console.log(i1.age);     //25
</script>  
</body>  
</html>  

posted @ 2018-05-11 11:43  徐同保  阅读(213)  评论(0编辑  收藏  举报