實現Storage

題目:實現Storage,使得該對象爲單例模式,並對localStorage進行封裝設置值setItem(key,value)和getItem(key)spa

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
相關文章
相關標籤/搜索