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.

1

2 Answers 2

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().

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

Comments

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.

2 Comments

in first case, everytime i click button, count value increases by 1.
you are right @VivekT my explanation was incorrect. I edited the answer and now I think it reflects reality

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.