我创建了下面的记忆作为概念证明。我想找到以下问题的答案:当我们修改闭包内的变量时,它是否会修改内存中的原始初始位置?或者当创建闭包时,它将所有值从原始位置复制到内存中的另一个位置?根据我对下面代码的测试,它会进行复制,但是,当闭包内的值发生变化时,原始位置也会受到影响。自己测试一下。
class Memoization {
cacheInitValue = new Map();
memoize(f) {
let cache = this.cacheInitValue;
return function (...args) {
let cacheKey = f.name + JSON.stringify(args);
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
let result = f.apply(this, args);
cache.set(cacheKey, result);
return result;
};
}
}
// Example of use #1: memoize simple function
// ----------------------------------------------------------------
function sum(...numbers) {
console.log(`sum(${numbers.join(',')}) was called`);
let total = 0;
for (let n of numbers) {
total += n;
}
return total;
}
// using:
let memoSum = new Memoization();
let cacheSum = memoSum.memoize(sum);
cacheSum(10,20); // get result from function (first time)
cacheSum(10,20); // get result from cache
// Now,take a look in the object memoSum has it property modified by the closure:
memoSum.cacheInitValue // the output is the keys of map changed inside the closure context.
// Now is the weirdest part, force a reset the cacheInitValue and see what happens:
memoSum.cacheInitValue = new Map();
// Yeah… call again the memoized:
cacheSum(10,20)
您没有覆盖
cache
。
initCacheValue
分配给 cache
。这两个变量现在指向同一个对象。initCacheValue
,但这并没有改变cache
。它仍然指向旧对象。原因:对象变量是对象的引用,而不是对象本身。