ES6 localStorage 類庫

無心中看到的,記錄下。es6

用到了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'));

 

關於classthis

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

  toString(){
    // ...
  }

  toValue(){
    // ...
  }
}

// 等同於

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

 

 

參考:http://es6.ruanyifeng.com/#docs/classspa

相關文章
相關標籤/搜索