GitHub 博客园 Nanakon

【JS模式】单体模式

《JavaScript模式》

  

/**
 * 单体(Singleton)模式的思想在于保证一个特定类仅有一个实例。这意味着当您第二次使用同一个类创建新对象的时候,每次得到与第一次创建对象完全相同对象
 * 在JS中没有类,只有对象。当您创建一个新对象时,实际上没有其他对象与其类似,因此新对象已经是单体了
 * 在JS中,对象之间永远不会完全相等,除非它们是同一个对象
 */
var obj = {
    myprop: 'my value'
}
var obj2 = {
    myprop: 'my value'
}
console.log(obj == obj2) // false

function Universe() {
    if (typeof Universe.instance === 'object') {
        return Universe.instance
    }
    this.start_time = 0
    this.bang = 'Big'
    Universe.instance = this
    // 构造函数隐式返回this
    //return this
}
var uni = new Universe()
var uni2 = new Universe()
console.log(uni === uni2)

function Universe2() {
    var instance = this
    this.start_time = 0
    this.bang = 'Big'
    Universe2 = function() {
        return instance
    }
}
var uni = new Universe2()
var uni2 = new Universe2()
var uni3 =  new Universe2()
var uni4 =  new Universe2() // ... 一直执行重写后的构造函数
console.log(uni === uni2)

function Universe3() {
    var instance
    Universe3 = function Universe3() {
        return instance
    }
    Universe3.prototype = this
    instance = new Universe3()
    instance.constructor = Universe3
    instance.start_time = 0
    instance.bang = 'Big'
    return instance
}
Universe3.prototype.nothing = true
var uni = new Universe3()
Universe3.prototype.everything = true
var uni2 = new Universe3()
console.log('====================\n', uni.nothing, uni.everything, uni.constructor.name, (uni.constructor === Universe3))

var Universe4
;(function() {
    var instance
    Universe4 = function Universe4() {
        if (instance) {
            return instance
        }
        instance = this
        this.start_time = 0
        this.bang = 'Big'
    }
})();
Universe4.prototype.nothing = true
var uni = new Universe4()
Universe4.prototype.everything = true
var uni2 = new Universe4()
console.log('====================\n', uni.nothing, uni.everything, uni.constructor.name, (uni.constructor === Universe4))

 

posted on 2014-01-09 22:29  jzm17173  阅读(421)  评论(0编辑  收藏  举报

导航

轻音