其他分享
首页 > 其他分享> > JS设计模式-单例模式

JS设计模式-单例模式

作者:互联网

JS设计模式-单例模式

面向对象:划分命名空间并将属性和方法组织在一起的一种方式

单例模式:只实例化一次。每次返回的实例都是同一对象

1.

function person(name){
    this.name = name
}

var getInstance = (function(){
    var instance
    return function(name){
        if(!instance) instance = new person(name)
        return instance
    }
})()

var person1 = getInstance('zhangsan') 
var person2 = getInstance('lisi')
console.log(person1.name); //zhangsan
console.log(person2.name); //zhangsan
console.log(person1 === person2);  //true

通过instance变量保存唯一的实例

2.

绑定在构造函数上

function person(name){
    this.name = name
}
person.getInstance = function(name){
    if(!this.instance) this.instance = new person(name)
    return this.instance 
}
var person1 = person.getInstance('zhangsan') 
var person2 = person.getInstance('lisi')
console.log(person1.name); //zhangsan
console.log(person2.name); //zhangsan
console.log(person1 === person2);  //true

3.

不推荐:实例化与单例相耦合

var person = (function(){
    var instance
    return function(name){
        if(new.target === undefined) throw new Error('请实例化')
        if(!instance){ 
            this.name = name
            instance = this
        }
        return instance
    }
})()
var person1 = new person('zhangsan') 
var person2 = new person('lisi')
console.log(person1.name); //zhangsan
console.log(person2.name); //zhangsan
console.log(person1 === person2);  //true
var person3 = person('hlela') //Uncaught Error: 请实例化

标签:console,name,person,JS,person2,instance,单例,var,设计模式
来源: https://www.cnblogs.com/qianduanxiaozhi1/p/15861131.html