【发布时间】:2018-09-27 07:43:34
【问题描述】:
我试图将函数 work 传递到装饰器中,它将函数调用保存在数组 work.calls 中。
功能:
work(a, b) {
console.log(a + b);
}
装饰者:
function decorator(func) {
func.calls = [];
return function(...args) {
func.calls.push(args);
return func.call(this, ...args);
}
}
装饰函数work:
work = decorator(work);
调用新函数:
work(1, 2); // 3
work(4, 5); // 9
for (let args of work.calls) {
console.log( 'call:' + args.join() ); // TypeError: work.calls is not iterable
}
work.calls 是一个数组,为什么不能迭代?
作为参考,还有另一个由其他人编写的实际工作的装饰器版本:
function decorator(func) {
function wrapper(...args) {
wrapper.calls.push(args);
return func.apply(this, arguments);
}
wrapper.calls = [];
return wrapper;
}
work(1, 2); // 3
work(4, 5); // 9
for (let args of work.calls) {
alert( 'call:' + args.join() ); // "call:1,2", "call:4,5"
}
wrapper 在这里做什么以及为什么这种方式有效?
【问题讨论】:
标签: javascript decorator typeerror