Sunday, November 20, 2016

JavaScript Closures

 function add() {

    var counter = 0;
    counter += 1;
}

add();
add();
add();
// the counter should now be 3, but it does not work !
-------------------------------
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();
// the counter is now 3 

No comments:

Post a Comment