Skip to content

Instantly share code, notes, and snippets.

@shellexy
Created June 8, 2012 09:25
Show Gist options
  • Save shellexy/2894686 to your computer and use it in GitHub Desktop.
Save shellexy/2894686 to your computer and use it in GitHub Desktop.
之前自用的 javascript localStorage 封装
//给添加 get、set、keys、values、items、update 方法:
window.localStorage.__proto__.get = function(key, defaultvalue) {
var txt = window.localStorage.getItem(key);
if (txt == null) {
return defaultvalue;
}
try{
return JSON.parse(txt);
} catch(e){
return txt;
}
}
window.localStorage.__proto__.set = function(key, obj) {
window.localStorage.setItem(key, JSON.stringify(obj));
}
window.localStorage.__proto__.keys = function() { return keys(window.localStorage) }
window.localStorage.__proto__.values = function() {
var result = [];
keys(window.localStorage).forEach( function(key) {
result.push(window.localStorage.get(key));
});
return result;
}
window.localStorage.__proto__.items = function() {
var result = [];
keys(window.localStorage).forEach( function(key) {
result.push([key, window.localStorage.get(key)]);
});
return result;
}
window.localStorage.__proto__.update = function(dict) {
keys(dict).forEach( function(key) {
window.localStorage.set(key, dict[key]);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment