【发布时间】:2018-01-26 19:14:14
【问题描述】:
当我意识到它没有按预期工作时,我正在制作一个装饰器函数来响应this question。该函数只是计算给定函数被调用的次数,并记录下来。
function countExecutions(fn) {
let count = 0;
return () => {
console.log("called",++count);
return fn.apply(this, arguments);;
}
}
var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // (a,b) => a+bundefined
我意识到这是因为arguments 引用了函数countExecutions 的参数,而不是我的内部匿名函数。 所以它记录了(a,b) => a+bundefined 而不是3。为什么我不能获取内部匿名函数的参数?
如果我给它一个名字,它会按预期工作:
function countExecutions(fn) {
let count = 0;
return function inner() {
console.log("called",++count);
return fn.apply(this, arguments);;
}
}
var test = countExecutions((a,b) => a+b);
var x = test(1,2);
console.log(x); // 3
【问题讨论】:
-
箭头函数没有
this和arguments -
应该也可以不命名它 - 只是做一个正常的
function() {} -
哦,对了!!所以这不是匿名,只是箭头
-
@jhpratt:我的问题与那个问题很接近,但我得到了更多有用的答案。所以我不想将其标记为重复。谢谢!
标签: javascript