closure function 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: what is closure in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
Example 3: closures in javascript
function OuterFunction() {
var outerVariable = 100;
function InnerFunction() {
alert(outerVariable);
}
return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc();
Example 4: closure in javascript
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Example 5: closure in javascript
var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value());
counter.increment();
counter.increment();
console.log(counter.value());
counter.decrement();
console.log(counter.value());
Example 6: closures in javascript
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();