Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading