Skip to content

Instantly share code, notes, and snippets.

@yy-dev7
Created January 9, 2018 06:20
Show Gist options
  • Save yy-dev7/4753dad68b14da2fa9f55e610f93c5d9 to your computer and use it in GitHub Desktop.
Save yy-dev7/4753dad68b14da2fa9f55e610f93c5d9 to your computer and use it in GitHub Desktop.
可以为sessionStorage,localStorage设置过期时间
class Storage {
constructor(strategy = 'internal') {
this.strategy = strategy
}
/**
* @param {string} key
* @param {any} val
* @param {number} maxAge 存储时间:ms
*/
set(key, val, maxAge = 0) {
const data = {
val,
expires: maxAge === 0 ? 0 : Date.now() + maxAge,
}
window[this.strategy][key.toString()] = JSON.stringify(data)
}
get(key) {
const data = window[this.strategy][key.toString()]
&& JSON.parse(window[this.strategy][key.toString()])
if (data) {
if (data.expires === 0) {
return data.val
}
if (Date.now() < data.expires) {
return data.val
}
this.remove(key)
return null
}
return null
}
remove(key) {
delete window[this.strategy][key.toString()]
}
}
// 全局变量
window.internal = window.internal || {}
const local = new Storage('localStorage')
const session = new Storage('sessionStorage')
const internal = new Storage('internal')
export default {
local,
session,
internal,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment