内容纲要
前言
在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。
和localStorage相似的还有sessionStorage,存储数据的方式还有indexedDb、cookies等!
原理
对浏览器本身的ocalStorage进行一层封装产生一个类,设置和获取数据均通过该类的示例暴露出的接口进行操作,简单来说,就是在set时不止存储数据,还存储数据的存活时间,而在get时,首先检测数据的有效性,当数据存在但过期时,返回空值,相当于数据不存在,并且执行数据的删除操作。。。
代码
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 过期时间,以分钟为单位
*/
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;
});
}
}
set(key, value, expired) {
/*
* set 存储方法
* @ param {String} key 键
* @ param {String} value 值,
* @ param {String} expired 过期时间,以毫秒为单位,非必须
*/
let source = this.source;
source[key] = JSON.stringify(value);
if (expired) {
source[`${key}__expires__`] = Date.now() + expired;
}
return value;
}
get(key) {
/*
* get 获取方法
* @ param {String} key 键
* @ param {String} expired 存储时为非必须字段,所以有可能取不到,默认为 Date.now+1
*/
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(key) {
/*
* remove 删除方法
* 不对外暴露
*/
const data = this.source,
value = data[key];
delete data[key];
delete data[`${key}__expires__`];
return value;
}
}
使用示例
待续。。。
发表评论