1A closure gives you access to an outer function’s scope from an inner function
2//example
3function init() {
4 var name = 'Mozilla'; // name is a local variable created by init
5 function displayName() { // displayName() is the inner function, a closure
6 alert(name); // use variable declared in the parent function
7 }
8 displayName();
9}
10init();
11
1function makeFunc() {
2 var name = 'Mozilla';
3 function displayName() {
4 alert(name);
5 }
6 return displayName;
7}
8
9var myFunc = makeFunc();
10myFunc();
11
1var counter = (function() {
2 var privateCounter = 0;
3 function changeBy(val) {
4 privateCounter += val;
5 }
6 return {
7 increment: function() {
8 changeBy(1);
9 },
10 decrement: function() {
11 changeBy(-1);
12 },
13 value: function() {
14 return privateCounter;
15 }
16 };
17})();
18
19console.log(counter.value()); // logs 0
20counter.increment();
21counter.increment();
22console.log(counter.value()); // logs 2
23counter.decrement();
24console.log(counter.value()); // logs 1
25