1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

ok how can the counter to be shared between two instance g1,g2? g1,g2 are separate variables, no? I accept your answer, I understand the counter variable is visible outside console.log function so, it is as global variable but not global at script file level because in closure? right?
It's not about g1 and g2, it's about the new Gadget() execution, it's execution update the counter, Just imagine, that the counter variable is stored somewhere, and any internal function that uses it, can update it, it something like, if you have a global variable, and there is a function update this value, whenever this function execute will update the last result of the global value, I wish that you understand it now.
Yes "whenever this function execute will update the last result of the global value, I wish that you understand it now" Thank you.
Please, check this example and you can understand what I mean, the closure will work like that jsfiddle.net/7n6gxsp3
I understand example Ok it's not about g1 and g2, it's about Gadget execution. However I have a doubt... when call new Gadget() context closure isn't created but it is the same if counter equal two at the end. Why? I Thought that (function(){ }) in two Gadget isn't the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.