ES6 localStorage 类库

无意中看到的,记录下。

用到了es6语法。支持在js中写构造函数

class CovLocalDB {
    constructor (name) {
        this.LS = null
        this.name = name
        this.checkLS()
        this.init(name)
    }

    checkLS () {
        if (window && window.localStorage) {
            this.LS = window.localStorage
            // console.log('localStorage is there?')
        } else {
            console.log('localStorage is there?')
        }
    }

    init (name) {
        if (this.LS) {
            if (this.LS[name]) {
                this.data = JSON.parse(this.LS[name])
            } else {
                this.data = {}
            }
        }
    }

    set (uri, data) {
        this.data[uri] = data
        if (this.LS) {
            this.LS[this.name] = JSON.stringify(this.data)
        }
    }

    get (uri) {
        if (this.data[uri]) {
            return this.data[uri]
        }
        return false
    }
}


const DB = new CovLocalDB('my-db')
DB.set('name', 'finley');
console.log(DB.get('name'));

 

关于class

class Point {
  constructor(){
    // ...
  }

  toString(){
    // ...
  }

  toValue(){
    // ...
  }
}

// 等同于

Point.prototype = {
  toString(){},
  toValue(){}
};

 

 

参考:http://es6.ruanyifeng.com/#docs/class

 

posted @ 2016-06-13 15:51  飞凡123  阅读(1704)  评论(0编辑  收藏  举报