closure scope javascript code example
Example 1: 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 2: javascript closure function example
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Example 3: closure and scope javascript
function outerFunction () {
const outer = `I'm the outer function!`
function innerFunction() {
const inner = `I'm the inner function!`
console.log(outer)
}
console.log(inner)
}