Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
Understanding static member variables in javascript 6

I don't understand because when I instantiate twice Gadget function object, the console print me final 2 not 1, counter is incremented.

var Gadget = (function(){
    var counter = 0;
    return function(){ console.log( counter += 1 );}
})();

var g1 = new Gadget();
var g2 = new Gadget();

If I don't immediate execute function expression I don't get any output:

var Gadget = (function(){
    var counter = 0;
    return function(){ console.log( counter += 1 );}
}); // <---- not immediate execute expression
var g1 = new Gadget();
var g2 = new Gadget();

No output.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

In the first block of code.

var Gadget = (function(){
var counter = 0;
    return function(){ console.log( counter += 1 );}
})();

var g1 = new Gadget();
var g2 = new Gadget();

Gadget will be equal the internal function, function(){ console.log( counter += 1 ), and because it will capture the counter value by Closure feature.

So the counter will be increment by Gadget execution.

In the second section

var Gadget = (function(){
var counter = 0;
    return function(){ console.log( counter += 1 );}
}); // <---- not immediate execute expression
var g1 = new Gadget();
var g2 = new Gadget();

Because the function doesn't immediately execute, the Gadget function will equal the outer function, not the internal function.

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda