• 【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('====================
    ', 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('====================
    ', uni.nothing, uni.everything, uni.constructor.name, (uni.constructor === Universe4))
  • 相关阅读:
    ajax跨域名
    js(鼠标键盘拖动事件)
    关于servlet转发和重新定向
    ztree的异步加载
    关于三层(dao,serviece,servlet)
    serclet监听器
    servlet(2)response常用方法
    servlet(1)request常用方法
    .post
    A1146 Topological Order
  • 原文地址:https://www.cnblogs.com/jzm17173/p/3512882.html
Copyright © 2020-2023  润新知