JavaScript Closures Example
HTML
<input type="button" value="Test Good" id="btnGood" />
<div id="outputGood"></div>
<br /><br />
<input type="button" value="Test Bad" id="btnBad" />
<div id="outputBad"></div>
JavaScript
$("#btnGood").click(function () {
$("#outputGood").html('');
var maple = 12;
var func = (function (maple) {
return function () {
$("#outputGood").append("<div>callback value = " + maple);
};
})(maple);
maple += 10;
func(); //execting callback
$("#outputGood").append("<div>current value = " + maple + "</div>");
});
$("#btnBad").click(function () {
$("#outputBad").html('');
var maple = 12;
var func = function () {
$("#outputBad").append("<div>callback value = " + maple);
};
maple += 10;
func(); //execting callback
$("#outputBad").append("<div>current value = " + maple + "</div>");
});