About
Closure in Javascript
The most common usage of closure in JavaScript is the module pattern.
Closures have access and can update their outer variables. Closures store their outer variables by references, not by copying their values. Updates are then visible to any construct that have access to them.
Example
Basic
A function is an object that creates a context and retains its state.
JavaScript provides a convenient literal syntax for constructing closures, the function expression.
function add(increment) {
var x = increment;
// The function expression is below after the return keyword
return function(y) {
return y + x;
};
}
var incrementBy2= add(2);
var incrementBy5= add(5);
console.log( incrementBy2(1) );
console.log( incrementBy5(10) );
Variable sharing
The function set and get properties are closures that have access to the same val variable.
function obj() {
var val = undefined;
let get = function() { return this.val; }
return {
set: function(val) { this.val = val; },
get: get,
add: function(val){this.val = this.get() + val;}
};
}
var o = obj();
console.log(o.get());
o.set(10);
console.log(o.get());
o.add(10);
console.log(o.get());