Skip to content

Instantly share code, notes, and snippets.

@lykkin
Created July 7, 2015 21:28
Show Gist options
  • Save lykkin/9831f8bb88eccd1a61e1 to your computer and use it in GitHub Desktop.
Save lykkin/9831f8bb88eccd1a61e1 to your computer and use it in GitHub Desktop.
closure based caching
'use strict'
function Obj() {}
Obj.prototype.getVal = getVal
Obj.prototype.clearCache = function clearCachedVal() {
console.log('clearing the cache')
this.getVal = getVal
}
function getVal(x) {
var _val
console.log('setting cached data')
this.getVal = function getCachedVal() {
console.log('serving cached data')
return _val
}
//do stuff with _val
_val = x
return _val
}
var obj = new Obj()
console.log(obj.getVal(1))
console.log(obj.getVal(2))
obj.clearCache()
console.log(obj.getVal(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment