1var counter = (function() { //exposed function references private state (the outer function’s scope / lexical environment) after outer returns.
2 var privateCounter = 0;
3 function changeBy(val) { privateCounter += val; }
4 return { increment: function() {changeBy(1); },
5 decrement: function() {changeBy(-1);},
6 value: function() {return privateCounter; }
7 };
8})();
9
10counter.increment(); counter.increment();
11counter.decrement();
12counter.value(); // 1
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
1func main() {
2 x := 0
3 increment := func() int {
4 x++
5 return x
6 }
7 fmt.Println(increment())
8 fmt.Println(increment())
9}
1function add(a) {
2 return function(b) {
3 return a + b;
4 };
5 }
6
7 let addTen = add(10);
8 let addSeven = addTen(7);
9
10 console.log(addSeven); // 17
1def say():
2 greeting = 'Hello'
3
4 def display():
5 print(greeting)
6
7 display()
8Code language: Python (python)