

思考点
在 web 开发中,我们知道 cookie、session、localStorage都可以保存用户的数据,cookie的 domain、path 限制了 cookie 的跨域, 有数量和大小的限制,可以设置有效时间。 session是后台在浏览器注入一个设置了 httponly 的不可读取的 cookie , session data由后台保存在数据库或者内存中,在web中,session 是靠 cookie 作为唯一标示来实现的,也可以设置过期时间。 localStorage 是 H5 的数据存储办法, 也是有大小限制的,但是不可以设置过期时间。
从我们接触前端起,第一个熟悉的存储相关的Cookie或者来分析我们生活中密切相关的淘宝、物流、闹钟等事物来说起吧,
以上种种,我们能得出一个结论任何一件事、一个行为动作,都有一个时间、一个节点,甚至我们可以黑localStorage,就是一个完善的API,为什么不能给一个设置过期的机制,因为sessionStorage、Cookie并不能满足我们实际的需求。
实现思路
抱歉,黑localStorage不完善,有点夸张了,综合上述的总结,问题就简单了,给localStorage一个过期时间,一切就都so easy ?到底是不是,来看看具体的实现吧:
简单回顾
//示例一:
localStorage.setItem('test',1234567);
let test = localStorage.getItem('test');
console.log(typeof test, test);
//示例二:
localStorage['name'] = '苏南';
console.log(localStorage['name']);
/*
重写 set(存入) 方法:
具体来看一下代码 :
set(key, value, expired) {
/*
* set 存储方法
* @ param {String} key 键
* @ param {String} value 值,
* @ param {String} expired 过期时间,以分钟为单位,非必须
* @ 由@IT·平头哥联盟-首席填坑官∙苏南 分享
*/
let source = this.source;
source[key] = JSON.stringify(value);
if (expired){
source[`${key}__expires__`] = Date.now() + 1000*60*expired
};
return value;
}重写 get(获取) 方法:
具体来看一下代码 :
get(key) {
/*
* get 获取方法
* @ param {String} key 键
* @ param {String} expired 存储时为非必须字段,所以有可能取不到,默认为 Date.now+1
* @ 由@IT·平头哥联盟-首席填坑官∙苏南 分享
*/
const source = this.source,
expired = source[`${key}__expires__`]||Date.now+1;
const now = Date.now();
if ( now >= expired ) {
this.remove(key);
return;
}
const value = source[key] ? JSON.parse(source[key]) : source[key];
return value;
}重写 remove(删除) 方法:
删除操作就简单了,;
remove(key) {
const data = this.source,
value = data[key];
delete data[key];
delete data[`${key}__expires__`];
return value;
}优化点:
class storage {
constructor(props) {
this.props = props || {}
this.source = this.props.source || window.localStorage
this.initRun();
}
initRun(){
/*
* set 存储方法
* @ param {String} key 键
* @ param {String} value 值,存储的值可能是数组/对象,不能直接存储,需要转换 JSON.stringify
* @ param {String} expired 过期时间,以分钟为单位
* @ 由@IT·平头哥联盟-首席填坑官∙苏南 分享
*/
const reg = new RegExp("__expires__");
let data = this.source;
let list = Object.keys(data);
if(list.length > 0){
list.map((key,v)=>{
if( !reg.test(key )){
let now = Date.now();
let expires = data[`${key}__expires__`]||Date.now+1;
if (now >= expires ) {
this.remove(key);
};
};
return key;
});
};
}
}总结:
