I have a very interesting case where I am not able to figure out if I have got the concept of closure wrong or is the Chrome debugger going wrong in its output.
The code is here https://jsfiddle.net/ygjfutck/ I have put everything in HTML because that is how I was replicating it on my local machine. I am using Google Chrome v49.
In the event handler for #button click, I am incrementing variable a
and putting the result in a HTML container. Interestingly, when I place a debug point using the Chrome Debug Tools, inside the event handler callback, and check the value of variable b
in the console, the console throws an error that variable b
is not defined.
Note: When I say check the value of b
in the console, it means that open up the chrome debug console and type b
there. It does not mean using console.log() or any other similar method
However if I change the event handler to this
$("#button").click(function() {
a = a + b;
$selector.html(a);
});
Then for the same debug point, b would now be defined in the console. I don't know what am I missing in terms of scope chain of event handlers or how the debugger views the same that is causing this behavior.
Note: If you are not able to place the debug point in jsfiddle, copy the HTML to a new file on your local machine and open it in Chrome.
The JS code for the above fiddle
<script>
function outer() {
var a;
var b;
var $selector;
var retObj = {
init: function() {
a = 10;
b = 5;
$selector = $("#id");
attachEventHandlers();
}
};
function attachEventHandlers() {
$("#button").click(function() {
//place a debug point here and then in the console
//b would not be defined
//change the below statement to a = a+b, and in the console
//b would be defined with the correct value
a = a + 1;
console.log(a);
$selector.html(a);
});
}
return retObj;
}
var obj = outer();
obj.init();
</script>
Screenshot attached for the error (when running the same HTML on a separate page outside JSFiddle)