首页 > Web开发 > 详细

【JS模式】单体模式

时间:2014-01-14 19:48:20      阅读:485      评论:0      收藏:0      [点我收藏+]

《JavaScript模式》

  

bubuko.com,布布扣
/**
 * 单体(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))
bubuko.com,布布扣

【JS模式】单体模式

原文:http://www.cnblogs.com/jzm17173/p/3512882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!