KingKongFrog
KingKongFrog

Reputation: 14429

Javascript closure, calling function different ways

I'm able to call this closure as so:

var increment = (function () {
  var test = 0;

  return function () {
    test++;
    console.log(test);

  }

})();
increment(); //1
increment(); //2

However how do I call this using regular function syntax?

function increment() {
   var test = 0;

   return function () {
     test++;
     console.log(test);
   }
}
increment()(); 1
increment()(); 1

Upvotes: 0

Views: 196

Answers (2)

kkemple
kkemple

Reputation: 992

you are returning a function so it would be

var inc = increment();
inc();
inc();

here is a fiddle http://jsfiddle.net/kkemple/hLQ3x/

Upvotes: 0

elclanrs
elclanrs

Reputation: 94121

Whenever you call increment() you create a "new counter", so the second example is not the same, you're creating 2 different instances.

You'd have to create an instance first, then use that:

var inc = increment();

inc(); // 1
inc(); // 2

Upvotes: 5

Related Questions