js 单例模式

来源:互联网 发布:兰亭序真迹在哪里 知乎 编辑:程序博客网 时间:2024/05/20 09:48

1.  使用静态属性

<pre name="code" class="javascript">function Universe() {    if(typeof Universe.instance === "object") {
        return Universe.instance;
    }    this.start_time = 0;    this.bang = "big";    Universe.instance = this;}

缺点:Universe.instance是公开的

2. 使用闭包

function <span style="font-family: Arial, Helvetica, sans-serif;">Universe</span><span style="font-family: Arial, Helvetica, sans-serif;">() {</span>    var instance = this;    this.start_time = 0;    this.bang = "big";    Universe = function() {        return instance;    }}
缺点:prototype只能使用第一个实例定义之前的

3. 调整后

function Universe() {    var instance;    Universe = function() {        return instance;    }    Universe.prototype = this;    Universe.constructor = Universe;    instance = new Universe();    instance.start_time = 0;    instance.bang = "big";    return instance;}

4. 使用闭包调整

var Universe;(function () {    var instance;    Universe = function() {        if(instance) {            return instance;        }        instance = this;        this.start_time = 0;        this.bang = "big";    }}());


0 0
原创粉丝点击