purpose of closures in javascript code example
Example 1: closure in js
A closure gives you access to an outer function’s scope from an inner function
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();
Example 2: es6 closures
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value());
counter1.increment();
counter1.increment();
alert(counter1.value());
counter1.decrement();
alert(counter1.value());
alert(counter2.value());
Example 3: closure in javascript
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();