Created
September 1, 2016 12:19
-
-
Save 52cik/e24b951a680153f1319950c1aac7042f to your computer and use it in GitHub Desktop.
简易 localStorage/sessionStorage 封装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(window, undefined) { | |
// 编码 | |
function encode(str) { | |
return encodeURIComponent(JSON.stringify(str)); | |
} | |
// 解码 | |
function decode(str) { | |
if (undefined == str) { | |
return str; | |
} | |
try { // 解码可能失败 | |
str = JSON.parse(decodeURIComponent(str)); | |
} catch (e) { | |
str = undefined | |
} | |
return str; | |
} | |
var Storage = [localStorage, sessionStorage]; | |
// 取值,赋值,删除 | |
function ls(key, val, session) { | |
var s = Storage[session ? 1 : 0]; | |
if (undefined === val) { // 取值 | |
return decode(s.getItem(key)); | |
} else if (null === val) { | |
s.removeItem(key); | |
} else { | |
s.setItem(key, encode(val)); | |
} | |
} | |
// ls 别名 | |
function ss(key, val) { | |
return ls(key, val, true); | |
} | |
// 清理 | |
ls.clear = function(session) { | |
Storage[session ? 1 : 0].clear(); | |
}; | |
// ls.clear 别名 | |
ss.clear = function() { | |
ls.clear(true); | |
}; | |
window.ls = ls; | |
window.ss = ss; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment