首页 > 解决方案 > 使用装饰器函数,其余参数,调用和应用

问题描述

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)

这是关于使用装饰器功能。计算第一次调用,然后兑现并从现金中提取。我读过,那个 arguments 对象是使用 rest 参数的旧方法,它可以被替换。那么为什么当我尝试替换参数对象时let key = hash(arguments)

return function() {
    let key = hash(arguments); 
    if (cache.has(key)) {
    return cache.get(key);
}

休息参数,它不起作用......

实际上它有效,但只有在 add 时才有效,但如果在其他情况下发生变化(我的意思是参数),例如等...(...arguments),它不会改变。为什么?arrars

标签: javascript

解决方案


对于所有非箭头函数,都有一个局部变量,arguments请参见此处

没有arguments你可以通过使用休息参数来获取值

return function(...myArgs) {
    let key = hash(myArgs)
    ...

或者,如果您在解构后将参数传递给哈希函数,例如

let key = hash(...arguments)

将您的哈希函数更改为

function hash(hMin, hMax) {
  return hMin + ',' + hMax;
}

推荐阅读