I was making a decorator function in response to this question when I realized it was not working as expected. The function simply counts how many times given function is called, and logs it.
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
I realized this is because arguments
refer to the arguments of the function countExecutions
instead of my inner anonymous function. So it logs (a,b) => a+bundefined
instead of 3
. Why can't I get arguments of inner anonymous function?
If I give it a name, it works as expected:
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