繁体   English   中英

使用装饰器函数,休息参数,调用和应用

[英]Using decorator function, rest parameters, call and apply

 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);
}

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

实际上它有效,但只有在添加...(...arguments)时才有效,但如果在其他(我的意思是参数)上更改,例如arrars等,则不会。为什么?

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

没有arguments您可以使用其余参数获取值

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

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

let key = hash(...arguments)

将您的哈希函数更改为

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

'arguments object 这是使用 rest 参数的旧方法,它可以被替换'

实际上,它们是不同的。 任何用关键字“function”声明的函数都有一个对象“arguments”,可以在函数内部使用。 即使您在内部使用了 rest 运算符,它仍然可用以及您的 'rest' 数组。

function foo (...args) {
console.log(args) // returns an array when foo below is called [1,23,5]
console.log(arguments) // returns an object when foo below is called {"0":1,"1":23,"2":5}
}

foo(1,23,5)

使用箭头函数时,'arguments' 对象不可用。

通过在函数定义和调用中使用... ,您可以使用自己的名称而不是内置arguments

 let worker = { slow(min, max) { alert(`Called with ${min},${max}`); return min + max; } }; function cachingDecorator(func, hash) { let cache = new Map(); return function(...myArgs) { let key = hash(myArgs); if (cache.has(key)) { return cache.get(key); } let result = func.call(this, ...myArgs); 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM