Function call

I start with JavaScript, so please be patient =)

I am trying to write a function that counts the number of times it is called. That I am still a function with a counter that explicitly increments:

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 wonder how to call only ob();, so the function can automatically increase the calls made. Is this possible, and if so, how?

+5
source share
2 answers
var increment = function() {
    var i = 0;
    return function() { return i += 1; };
};

var ob = increment();
+7
source
ob = function (){  
  ++ob.i || (ob.i=1);
  return ob.i; 
}
0
source

All Articles