Monday, October 31, 2016

JavaScript: Function Closure

// persist this function so that it can be used multiple times
//   also maintains the context(data) inside the function
var incrementer = function IncrementerFn(seed) {
    var currVal = seed;

    var increment = function incrementFn(){
        return currVal++;
    }

    // return the pointer to the main function in this closure
    return increment;
}

var increment = incrementer(1000);
console.log(increment());
console.log(increment());
console.log(increment());

Output:
1000
1001
1002