var Gadget = function () {
// static variable/property
var counter = 0;
// returning the new implementation
// of the constructor
return function () {
console.log(counter += 1);
};
}(); // execute immediately
var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3
I debug this code and the var counter = 0; will not be executed during new Gadget(), and the output is 1,2,3.
var Gadget = function () {
// static variable/property
var counter = 0;
// returning the new implementation
// of the constructor
return function () {
console.log(counter += 1);
}();
}; // execute immediately
var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3
I debug this code the var counter = 0; will be executed during new Gadget(), and the output is 1,1,1.
this demo code is in javascript pattern, private static members. I have a little trouble to understand this.
What’s happening is this..
In the first one, you have the () at the END of the function, so the function is executed, and the return statement is stored in “var Gadget”. The return statement is the constructor you have- A function. So now, when you do new Gadget(), you’re executing that function. IE, the outside function is executed right away, setting counter=0, then the inner function is returned to the variable Gadget, and every time it’s run, it increments counter.
In the second one, however, you store the “outer” function into the “var Gadget”, but inside that function, you execute the inner function. So when you make a new Gadget, the counter is set to zero, then the return function is declared and then executed because of the () after it, hence incrementing counter, which was JUST set to 0, therefor it becomes 1.
I hope this makes sense. When you define a function and store it in a var, the function isn’t executed yet. It’s executed when you “execute” the var, such as
var(). But if you have a () after it, it is executed as a function, and whatever it RETURNS is stored into var.In fact, in the first code, g1, g2, and g3 will all be references to the same inner function, and in the second code, g1, g2, and g3 will be references to the Gadget function, as you expect, but then the inner function will have evaluated and return nothing.