SOURCE

/** 实现一个 Storage
 * 实现Storage,使得该对象为单例,基于 localStorage 进行封装。
 * 实现方法 setItem(key,value) 和 getItem(key)。
 */

/**
 * 静态方法版
 */
class Storage1 {
    constructor() {
        this.pools = {}
    }
    setItem(key, value) {
        this.pools[key] = value
    }
    getItem(key, value) {
        return this.pools[key]
    }
    static getInstance() {
        if (!Storage1.instance) {
            Storage1.instance = new Storage1()
        }
        return Storage1.instance
    }
}

Storage1.getInstance().setItem('key1', 'cat')
console.log(Storage1.getInstance().getItem('key1'))

/**
 * 闭包方法版
 */
function Storage2() {
    this.pools = {}
}
Storage2.prototype.setItem = function (key, value) {
    this.pools[key] = value
}
Storage2.prototype.getItem = function (key) {
    return this.pools[key]
}
Storage2.getInstance = function () {
    let instance = null
    return function () {
        if (!instance) {
            instance = new Storage2()
        }
        return instance
    }
}()
Storage2.getInstance().setItem('key1', 'dog')
console.log(Storage2.getInstance().getItem('key1'))

console 命令行工具 X clear

                    
>
console