实现Storage

题目:实现Storage,使得该对象为单例模式,并对localStorage进行封装设置值setItem(key,value)和getItem(key)

function Storage(){}
Storage.getInstance=(function(){
    var instance=null;
    return function(){
        if(!instance){
            instance=new Storage();
        }
        return instance
    }
})()
    
Storage.prototype.setItem=function(key,value){
    return localStorage.setItem(key,value);
}
Storage.prototype.getItem=function(key){
    return localStorage.getItem(key);
}
    
let ins1=Storage.getInstance();
let ins2=Storage.getInstance();
ins1.setItem('key',1);
console.log(ins2.getItem('key'));//1
console.log(ins2.getItem('key1'));//null
原文地址:https://www.cnblogs.com/xiaoan0705/p/11149213.html