let worker = {
slow(min, max) {
alert(`Called with ${min},${max}`);
return min + max;
}
};
function cachingDecorator(func, hash) {
let cache = new Map();
return function() {
let key = hash(arguments); //...arguments also works, but only with this name, another no, why?
if (cache.has(key)) {
return cache.get(key);
}
let result = func.call(this, ...arguments);
cache.set(key, result);
return result;
};
}
function hash(args) {
return args[0] + ',' + args[1];
}
worker.slow = cachingDecorator(worker.slow, hash);
alert( worker.slow(3, 5) ); // works
alert( "Again " + worker.slow(3, 5) ); // same (cached)
关于使用装饰器功能。先计算一次通话,然后将其兑现并从现金中提取。我读过,该参数对象是使用rest参数的旧方法,并且可以替换它。那为什么当我尝试替换let key = hash(arguments)
return function() {
let key = hash(arguments);
if (cache.has(key)) {
return cache.get(key);
}
休息参数,它不起作用...
实际上它是有效的,但仅当添加...(...arguments)
时有效,但如果在其他方面(我指的是参数)进行更改,例如arr
,ars
等。为什么?
对于所有非箭头功能,都有一个局部变量arguments
,请参见here
此外,如果在像解构后将参数传递给哈希函数,则>
let key = hash(...arguments)
将您的哈希函数更改为
function hash(hMin, hMax) {
return hMin + ',' + hMax;
}
'arguments对象是使用rest参数的旧方法,它可以是已替换”