Closure is a locally declared variable related to a function which stays in memory when the function has returned.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
functiongreet(message){
console.log(message);
}
functiongreeter(name,age){
returnname+" says howdy!! He is "+age+" years old";
}
// Generate the message
varmessage=greeter("James",23);
// Pass it explicitly to greet
greet(message);
Thisfunctioncan be better represented by using closures
functiongreeter(name,age){
varmessage=name+" says howdy!! He is "+age+" years old";
returnfunctiongreet(){
console.log(message);
};
}
// Generate the closure
varJamesGreeter=greeter("James",23);
// Use the closure
JamesGreeter();
|