var Singleton = function(name) {
    this.name = name;
    this.instance = null;
    console.log("construct");
    console.log(this);
};

Singleton.prototype.getName = function() {
    alert(this.name);
};

Singleton.getInstance = function(name) {   //这里的this 指的是 Singleton , 刚开始以为是new出来的实例的this. 
    console.log("=[=")
    console.log(this.instance);
    console.log(this);
 console.log("=]=")
    if (!this.instance) {
        console.log(2);
        this.instance = new Singleton(name);
    }

    return this.instance;
};

var a = Singleton.getInstance('seven1');
var b = Singleton.getInstance('seven2');
 console.log("=a=")
console.log(a);
 console.log("=b=")
console.log(b)

输出:

=[=
VM598:14 undefined
VM598:15 ƒ (name) {
this.name = name;
this.instance = null;
console.log("construct");
console.log(this);
}
VM598:16 =]=
VM598:18 2
VM598:4 construct
VM598:5 Singleton {name: "seven1", instance: null}
VM598:13 =[=
VM598:14 Singleton {name: "seven1", instance: null}
VM598:15 ƒ (name) {
this.name = name;
this.instance = null;
console.log("construct");
console.log(this);
}
VM598:16 =]=
VM598:27 =a=
VM598:28 Singleton {name: "seven1", instance: null}
VM598:29 =b=
VM598:30 Singleton {name: "seven1", instance: null}

 

保证一个类仅有一个实例,并且提供一个访问它的全局访问点。

 

posted on 2018-01-24 13:37  海米柚  阅读(100)  评论(0编辑  收藏  举报