localStorage简单封装

316 阅读1分钟
  • 简单的封装了下localStorage:
  • 一是使其能够设置过期时间
  • 二是如果存储的是对象的话,可以直接返回对象(由于是直接使用JSON.stringify(),所以是存在弊端的)
  • 代码如下:
class CoStorage {
  constructor() {
    this.options = {
      startTime: 0, // 开始时间(ms)
      duration: 0   // 有效持续时间(ms)
    };
  }
  setItem(name, data, duration) {
    this.options.startTime = new Date().getTime();
    this.options.duration = duration;
    let value = null;
    if (typeof data !== 'object' || data == null) {
      value = data;
    } else {
      value = JSON.stringify(data);
    }
    localStorage.setItem(name, value);
  }

  getItem(name) {
    let item = localStorage.getItem(name);
    try {
      item = JSON.parse(item);
    } catch (e) {
      item = item;
    }
    if (this.options.startTime > 0) {
      const now = new Date().getTime();
      if (now - this.options.startTime > this.options.duration) {
        this.removeItem(name);
        return null;
      }
    }
    return item;
  }

  removeItem(name) {
    localStorage.removeItem(name);
  }

  clear() {
    localStorage.clear();
  }
}