Understanding static member variables in javascript 6

Viewed 30

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.

1 Answers

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.

Related