【发布时间】:2023-03-13 14:32:02
【问题描述】:
如果有人能以简单的方式逐步解释这里发生的事情,那将非常有帮助。我知道memoize() 正在缓存函数,但我需要更好地理解。谢谢!
var memoize = function (f) {
var cache = {};
return function () {
var str = JSON.stringify(arguments);
cache[str] = cache[str] || f.apply(f, arguments);
return cache[str];
};
};
var mUser = memoize(function(x){
return function() {
return x;
};
});
var x = mUser(1);
var y = mUser(2);
console.log(x()); //1
console.log(y()); //2
编辑:我保留原件作为记录。但是发布修改后的代码和我对它的理解。如果我是对是错,我需要意见和解释。
var memoize = function (injected) {
var cache = {};
return function closure_with_access_to_cache () {
var str = JSON.stringify(arguments);
cache[str] = cache[str] || injected.apply(injected, arguments);
console.log(cache);
return cache[str];
};
};
var memoizeUser = memoize (function injected(a) {
return function closure_with_access_to_a () {
return a;
};
});
memoizeUser();
让我们试着回溯一下。
首先,当memoizeUser(); 语句被执行时,memoizeUser 代表什么或者首先调用哪个函数?
var memoizeUser = ... 是一个函数表达式,表示它没有被提升。
所以,memoize 被调用。
但是,var memoize = ... 也是一个函数表达式。仔细看,它是一个闭包closure_with_access_to_cache,并在调用时接收传递给memoizeUser 的参数。
在这个closure_with_access_to_cache中,第一次cache是空的,所以injected.apply(injected, arguments)被执行并得到另一个闭包closure_with_access_to_a作为返回值。该值存储到cache,然后返回。所以,memoizeUser 实际上变成了closure_with_access_to_a,其中a 等于传递给memoizeUser 的值。
让我们看看一些通话和日志。
console.log(memoizeUser());
{ '{}': [Function: closure_with_access_to_a] }
[Function: closure_with_access_to_a]
缓存键是空对象,因为没有任何东西作为参数传递给memoizeUser()。 memoizeUser() 返回函数 closure_with_access_to_a 记录。
console.log(memoizeUser()());
{ '{}': [Function: closure_with_access_to_a] }
undefined
memoizeUser() 返回函数 closure_with_access_to_a,它被调用并记录为 undefined,它是 a 的值,因为没有任何东西传递给 memoizeUser。
memoizeUser(1);
{ '{"0":1}': [Function: closure_with_access_to_a] }
除了 a 的值为 1 之外,与上面类似。
console.log(memoizeUser(1)());
{ '{"0":1}': [Function: closure_with_access_to_a] }
1
除了a 的值为 1 之外,与上面类似。
【问题讨论】:
-
可以看看 Map 和其他参数,它使东西更加防弹......
-
@Jonasw 感谢您的建议!