Create a method in a function involved

6

asked by anonymous 06.02.2014 / 14:01

1 answer

3

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);

link

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);

link

    
06.02.2014 / 14:10