Create a method in an involved function

Asked

Viewed 730 times

6

The allows you to create involve functions as can be seen in that SOEN response and in that reply.

With the help of these answers I managed to involve a function spy, as in the code below:

function spy(func) {
  return function(){
    var args = Array.prototype.slice.call(arguments);
    return func.apply(this, args);
  }
}

what I want to do now is this, when I assign this "wrapper" (wrapper), I want it to have an accessible object that generates me a report, for example:

var spied = spy(umaFuncao);
var report = spied.report();

And this object has accessible properties, such as the number of times the method involved has been called, for example:

console.log(report.totalCalls);//Será impresso no console o número de vezes que o método foi chamado

How could I do that? This is a question that can be found in codewars and I thought it would be interesting to bring here.

1 answer

3


You can hang the properties you want to monitor on the 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);

http://jsfiddle.net/8k4ph/1/

If you really care about a method and the object report, 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);

http://jsfiddle.net/8k4ph/2/

  • the path seems to be more or less there, but if I wanted the report, instead of an object being a method that returns an object? I think I misexpressed myself in my question.

  • 1

    I understood, but in the background not even the object would be necessary... totalCalls could be hung on Spied. But I will edit to do what you asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.