SOURCE

// 定义Storage
class Storage {
    static getInstance() {
        // 判断是否已经new过1个实例
        if (!Storage.instance) {
            // 若这个唯一的实例不存在,那么先创建它
            Storage.instance = new Storage()
        }
        // 如果这个唯一的实例已经存在,则直接返回
        return Storage.instance
    }
    getItem (key) {
        return localStorage.getItem(key)
    }
    setItem (key, value) {
        return localStorage.setItem(key, value)
    }
}

const storage1 = Storage.getInstance()
const storage2 = Storage.getInstance()

storage1.setItem('name', '李雷')
// 李雷
storage1.getItem('name')
// 也是李雷
storage2.getItem('name')

// 返回true
console.log(storage1 === storage2)


/**
 * 闭包版
 */


//先实现一个基础StorageBase类,把getItem()和
//SetItem()方法放在它的原型链上


function StorageBase(){}


StorageBase.prototype.getItem =  function(key){

    return localStorage.getItem(key)
}


StorageBase.prototype.setItem =  function (key,value){

    return localStorage.setItem(key,value)
}


const  Storage = (function(){
    let  instance = null

    return function(){
        //判断自由变量是否为 null
        if(!instance){
            instance =  new StorageBase()
        }

        return instance    
    }
})()


//

const storage1 =  new Storage()

const storage2 =  new Storage()


storage1.setItem('name','李雷')


Storage1.getItem('name');

Storage2.getItem('name')

storage1===storage2
console 命令行工具 X clear

                    
>
console