javascript - 使用装饰器函数,其余参数,调用和应用
问题描述
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)
,它不会改变。为什么?arr
ars
解决方案
对于所有非箭头函数,都有一个局部变量,arguments
请参见此处
没有arguments
你可以通过使用休息参数来获取值
return function(...myArgs) {
let key = hash(myArgs)
...
或者,如果您在解构后将参数传递给哈希函数,例如
let key = hash(...arguments)
将您的哈希函数更改为
function hash(hMin, hMax) {
return hMin + ',' + hMax;
}
推荐阅读
- reactjs - index.html 在从 create-react-app 构建纱线后仅显示一些组件
- javascript - 如何以更简洁的方式编写嵌套订阅?
- java - javafx 如何根据辅助场景中的更改更改/刷新主场景及其控件?
- python - 通过flask和wtforms MultipleFileField保存多个文件
- html - 使用 jQuery toggle() 后如何响应地隐藏菜单?
- excel - Excel - 基于另一个单元格返回单元格的值
- php - 将 PHP 脚本输出写入 txt 文件
- c# - 尝试获取页面上的所有 iFrame,但遇到 ProcessEndedUnexpectedlyException。试过异步函数,只解析一个 iFrame。我怎样才能解决这个问题?
- node.js - 在运行 .then 响应之前,带有 axios 调用的 for 循环返回,因此它返回一个空数组
- arrays - 解析 JSON 对象时输出带有方括号和大括号的本地存储对象