不明白为什么这个函数能实现缓存?
第一:keys是局部变量,每次调用createCache(),keys都被初始化为空数组。
第二:cache闭包函数每次通过createCache()(key, value)即便接收了属性名和属性值key和value;
但返回的只是属性值, 每次createCache()也得不到属性值呀, 因为每次调用cache都被重新声明, 也不可能保存前一个alue值呀.
/**
- Create key-value caches of limited size
- @returns {Function(string, Object)} Returns the Object data after storing it on itself with
- property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
- deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
0 个回复