一個簡單的Js緩存

var SimpleCache = function() {
	_this = this;
	_this.map = {};
	// 緩存
	this.add = function(key, value) {
		_this.map[key] = value;
	};
	this.addExp = function(key, value, timeout) {
		_this.map[key] = value;
		setTimeout(function() {
			_this.del(key);
		},
		timeout)

	};
	this.getValue = function(key) {
		if (_this.isExt(key)) {
			return _this.map[key];
		}
		return null;
	};
	this.getAll = function() {
		return _this.map;
	};
	this.del = function(key) {
		if (_this.isExt(key)) {
			delete _this.map[key];
		}
	};
	this.updata = function() {
		if (!_this.isExt(key)) {
			return;
		}
		_this.map[key] = value;
	};
	this.isExt = function(key) {
		if (!_this.map[key]) {
			return false;
		}
		return true;
	};
}

一個帶過期的緩存

let sc = new SimpleCache();
      sc.add("name","Tim");
      console.log(sc.getValue("name"));


      sc.addExp("names","Tim1",5000);

      setTimeout(function(){
        console.log(sc.getValue("names"));

      },2000)

      setTimeout(function(){
        console.log(sc.getValue("nanamesme"));
      },6000)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章