1function makeAdder(x) {
2 return function(y) {
3 return x + y;
4 };
5}
6
7var add5 = makeAdder(5);
8var add10 = makeAdder(10);
9
10console.log(add5(2)); // 7
11console.log(add10(2)); // 12
1var makeCounter = 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
19var counter1 = makeCounter();
20var counter2 = makeCounter();
21alert(counter1.value()); /* Alerts 0 */
22counter1.increment();
23counter1.increment();
24alert(counter1.value()); /* Alerts 2 */
25counter1.decrement();
26alert(counter1.value()); /* Alerts 1 */
27alert(counter2.value()); /* Alerts 0 */
28
1function OuterFunction() {
2
3 var outerVariable = 100;
4
5 function InnerFunction() {
6 alert(outerVariable);
7 }
8
9 return InnerFunction;
10}
11var innerFunc = OuterFunction();
12
13innerFunc(); // 100
14