Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!