Recently, I encountered an issue while trying to track how many times a particular JavaScript function got called. The approach of adding an attribute to the function worked perfectly fine for keeping count, but surprisingly, I faced difficulty when attempting to access this count value from outside the function. Why is it that g.n
doesn't return 2
in my scenario?
var keepCount = function (fn) {
fn.calls = 0
return function () {
fn.calls++;
console.log('Function was executed ' + fn.calls + ' times')
return fn.apply(null, arguments)
}
}
var func1 = function (x) { return x };
var func2 = keepCount(func1)
console.log(func2(1)); // Function was executed 1 time, returns 1
console.log(func2(2)); // Function was executed 2 times, returns 2
console.log(func2.calls); // Undefined