实现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

 

posted @ 2019-07-08 09:03  安xiao曦  阅读(494)  评论(0编辑  收藏  举报