-
Notifications
You must be signed in to change notification settings - Fork 3
/
29.2 Closures in JS.html
34 lines (30 loc) · 1.54 KB
/
29.2 Closures in JS.html
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
<!DOCTYPE html>
<html lang="en">
<head><title>Closures in JavaScript</title>
</head>
<body>
<strong>
See Program 29 Closures in JS and 29.1 Closures in JS before this program
</strong>
<script>
function x(){
var a=20;
function y(){ // or return function y(){
console.log(a); //console.log(a)
} // } this is same as return y;
return y;
}
var z=x(); //we are calling function x and it returns y , which is put inside z and x() is gone.
// Now z contains y()
console.log(z); // o/p function y() code
//When calling z ; (we can call this although its a variable but now it contains function in it)
z(); // i.e we are actually calling function y()
// o/p : ? , it will print 20 , Here comes closure into picture. When functions are returned
//from another function they still maintain their lexical scope, they remember where they were
// actually present. So y() remembers from where it came and it remembers their was something a and it will look for its value
//when function y() was returned not just the function code was returned but
//the whole closure was also returned and it was put into z. and when you execute z() it still remembers
// the reference to a and prints value of 'a'
</script>
</body>
</html>