无法清除JavaScript记忆化(Memoized)函数缓存,求技术解决方案
解决记忆化函数缓存清除问题
你当前的问题是memoizedSquare.clear()报错,因为clear函数定义在返回的匿名函数内部,属于局部函数,外部无法访问。下面是修改后的可行方案:
修改后的记忆化函数
function memoize(func) { let cache = {}; // 定义返回的记忆化函数 const memoizedFunc = function() { const key = JSON.stringify(arguments); if(cache[key]) { return cache[key]; } const result = func.apply(this, arguments); cache[key] = result; return result; }; // 给记忆化函数挂载clear方法,用于清除缓存 memoizedFunc.clear = function() { cache = {}; }; return memoizedFunc; }
验证修改后的代码运行效果
使用你原有的测试代码,现在memoizedSquare.clear()可以正常执行:
function square(num) { console.log('calling square of', num); return num*num; } const memoizedSquare = memoize(square); memoizedSquare(1); // 打印 "calling square of 1",返回1 memoizedSquare(1); // 直接返回1,无打印 memoizedSquare(2); // 打印 "calling square of 2",返回4 memoizedSquare.clear(); // 清除缓存 memoizedSquare(2); // 再次打印 "calling square of 2",返回4(缓存已清空,重新计算) memoizedSquare(3); // 打印 "calling square of 3",返回9
为什么之前的方案无效?
你尝试的prototype、call、bind等方法之所以没用,核心原因是:
- 原代码中
clear是嵌套在返回函数内部的局部函数,不属于返回函数的属性或原型链 - 外部无法直接访问函数内部的局部变量/函数,必须通过挂载到返回函数对象上的方式暴露方法
内容的提问来源于stack exchange,提问作者Warren Buffet
相关产品推荐
相关产品推荐

