You can hang the properties you want to monitor on the very object / function that is returning. For example:
function spy(func) {
function spied(){
var args = Array.prototype.slice.call(arguments);
spied.totalCalls++;
return func.apply(this, args);
}
spied.totalCalls = 0;
return spied;
}
var spied = spy(function(){});
spied();
spied();
spied();
console.log(spied.totalCalls);
If you are really concerned about a method and the report object, take advantage of the closure being created:
function spy(func) {
var report = { totalCalls: 0 };
function spied(){
var args = Array.prototype.slice.call(arguments);
report.totalCalls++;
return func.apply(this, args);
}
spied.report = function() {
return report;
}
return spied;
}
var spied = spy(function(){});
var report = spied.report();
spied();
spied();
spied();
console.log(report.totalCalls);