如果有人能以简单的方式逐步解释这里发生的事情,那将非常有帮助。我知道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
Run Code Online (Sandbox Code Playgroud)
编辑:我保留原件以供记录。但发布修改后的代码和我对它的理解。如果我是对还是错,我需要意见以及对其中任何一个的一些解释。
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); …Run Code Online (Sandbox Code Playgroud)