我正在尝试通过向其添加属性来计算函数被调用的次数。计数器工作正常,但我无法从函数外部访问其值 - 见下文。为什么g.n
不会在我的案例中返回2
?
var countFunc = function (func) {
func.n = 0
return function () {
func.n++;
console.log('called ' + func.n + ' times')
return func.apply(null, arguments)
}
}
var f = function (x) { return x };
var g = countFunc(f)
console.log(g(1)); //called 1 times, 1
console.log(g(2)); //called 2 times, 2
console.log(g.n); //undefined
答案 0 :(得分:0)
只需将计数器保存到新创建的函数而不是原始函数。
var countFunc = function (func) {
function wrapped () {
wrapped.n++;
console.log('called ' + wrapped.n + ' times')
return func.apply(null, arguments)
};
wrapped.n = 0;
return wrapped;
}
var f = function (x) { return x };
var g = countFunc(f)
console.log(g(1)); //called 1 times, 1
console.log(g(2)); //called 2 times, 2
console.log(g.n); //2