2

i am trying to understand closure.How would you explain behavior of these two scenarios.

Scenario 1

<input type="button" value="Click me" onclick="alert(handle())"/>
<script>
var handle = (function(){
  var count = 0;
  return function(){
    return ++count ;
  }
})();
</script>

Scenario 2

<input type="button" value="Click me" onclick="alert(handle()())"/>
<script>
var handle = function(){
  var count = 0;
  return function(){
    return ++count ;
  }
};
</script>

aren't both scenarios same? why in first scenario outer function is called only one time and after first click, on every click inner function is called.

VivekT
  • 81
  • 2
  • 13
  • 2
    [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – adeneo Sep 09 '17 at 16:53

2 Answers2

1

In the first case you create function handle that returns a function, and then you call that function so the handle method being used is the closure inside handle, which keeps track of the variables inside the closure scop(count). The second case you are returning a new closure each time because calling handle() returns a new closure. Therefore you are resetting the scope on each button click since you are creating a new closure to be called with handle().

Garrigan Stafford
  • 1,331
  • 9
  • 20
0

in the first case, you are evaluating the function, so what you are getting is the inner function, which will increment the counter every time it is called.

In the second case however, handle contains the outer function, so if you call that, you will get the inner function, which in turn will increment the counter when called.

So both snippets are called handle, when they are actually doing different things.

Mario F
  • 45,569
  • 6
  • 37
  • 38