在读vue源码时,遇到cached方法,如下:
// 在src/shared/until.js中
export function cached (fn: Function): Function {
const cache = Object.create(null)
return function cachedFn (str: string): any {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
上面这个方法在很多其他方法中有运用,如
//驼峰化以连字符分隔的字符
const camelizeRE = /-(\w)/g
export const camelize = cached((str: string): string => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
//大写字符串
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
网上查询了说是cached方式加快数据的读取速度,加做缓存策略
;
但是并不能理解,有大神可以讲解下,该方法的原理吗?
// 原理函数闭包
1 step 把 执行 函数 得到结果 result, 并且 此时 把 ‘ui’作为key, reault 作为value, 放到 cache 对象里, 2 step 再调 这个函数, 结果直接 取 chche['ui'] ,及相当于少走一步 fk 函数。