Function count calls

2019-02-22 09:21发布

I'm a beginner with JavaScript so please be patient =)

I am trying to write a function that counts the number of times it is called. What I have so far is a function with a counter that is incremented explicitly:

var increment = function () {
    var i = 0;
    this.inc = function () {i += 1;};
    this.get = function () {return i;};
};

var ob = new increment();
ob.inc();
ob.inc();
alert(ob.get());

But I'm wondering how to call only ob();, so the function could increment calls made to itself automatically. Is this possible and if so, how?

3条回答
Animai°情兽
2楼-- · 2019-02-22 09:44
var increment = function() {
    var i = 0;
    return function() { return i += 1; };
};

var ob = increment();
查看更多
Bombasti
3楼-- · 2019-02-22 09:49

Wrap a counter to any function:

/**
 * Wrap a counter to a function
 * Count how many times a function is called
 * @param {Function} fn Function to count
 * @param {Number} count Counter, default to 1
 */
function addCounterToFn(fn, count = 1) {
  return function () {
    fn.apply(null, arguments);
    return count++;
  }
}

See https://jsfiddle.net/n50eszwm/

查看更多
贼婆χ
4楼-- · 2019-02-22 09:50
ob = function (){  
  ++ob.i || (ob.i=1);
  return ob.i; 
}
查看更多
登录 后发表回答