Pregunta

I'm following wikipedia's example:

var counter = (function(){
  var i = 0;

  return {
    get: function(){
      return i;
    },
    set: function( val ){
      i = val;
    },
    increment: function() {
      return ++i;
    }
  };
}());

I understand that there's a closure inside which holds the stack frame with the i variable and I can create multiple counters - that's clear. But why is IIFE syntax used here? If it rewrite the code without it, it works the same way:

var counter2 = function(){
  var i = 0;

  return {
    get: function(){
      return i;
    },
    set: function( val ){
      i = val;
    },
    increment: function() {
      return ++i;
    }
  };
};

c2 = counter2();

I'd appreciate an explanation on what is IIFE doing in wikipedia's example.

¿Fue útil?

Solución

The difference is that you actually define a function. In your variant the counter2 will still be in memory as the prototype for object c2.

Iffys are used when you only to create a single object of a certain type and not a prototype for later reuse.

Otros consejos

Calling the function immediately lets it be anonymous. The gain is that you don't clutter the namespace with a function name you won't need afterwards.

There's no other difference, it might look like a detail, but why would would name this function if you don't reuse it ?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top