-
Notifications
You must be signed in to change notification settings - Fork 3
/
29.1 Closures in JS.html
45 lines (38 loc) · 1.58 KB
/
29.1 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
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html lang="en">
<head><title>Closures in JavaScript</title>
</head>
<body>
<strong>
See Program 29 Closures in JS before this program
</strong>
<script>
//use debugger amd see from video to understand concept better
// closure gives you access to an outer function's scope from an inner function.
//In JS, a closure is created every time a function is created at function creation time
function x(){
var a=10;
function y(){
console.log(a); // o/p 10 and this is what closure is
// closure basically means that a function bind/group together with its lexical environment (parent)
// or function along with its lexical scope forms a "closure" thats known as closure
// here Inside y() function, it forms a closure with the varibale 'a' which is the part of x()
// lexical scope/function and it has access to its parents lexical scope that's why it prints 10
}
y();
}
x();
function test(){
var x=20;
function b(){
console.log(x);
}
return b; //this will return whole function b()
//return b(); //o/p: 20
}
var c=test();
console.log(c); // o/p function b()'s code
// now study from next code 29.2 closures in JS
</script>
</body>
</html>