forked from learning-zone/javascript-basics
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclosures.html
More file actions
47 lines (41 loc) · 1.42 KB
/
closures.html
File metadata and controls
47 lines (41 loc) · 1.42 KB
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
46
47
<!DOCTYPE html>
<html>
<head>
<title>Closures, Lexical Scope and Dynamic Scope</title>
</head>
<script>
/***
* A closure is the combination of a function bundled together (enclosed) with references
* to its surrounding state (the lexical environment). In other words, a closure gives
* you access to an outer function’s scope from an inner function.
*
* Lexical Scope:- In lexical scoping free variables must belong to a parent scope.
*
* Dynamic Scope:- In dynamic scoping free variables must belong to the calling scope
*
* ***/
var Person = function(name) {
var text = 'Hello ' + name; // Local variable
var say = function() {
// Closure makes this function private to this class
console.log("Using Closure: "+text);
};
return say;
};
var obj = new Person('Pradeep');
obj();
// ---------------
// Lexical Scope
// ---------------
function add(x) { // template of a new scope, x is bound in this scope
return function (y) { // template of a new scope, x is free, y is bound
return x + y; // x resolves to the parent scope
};
}
var sum = add(10); // create a new scope for x and return a function
console.log("Using Lexical Scope: "+sum(20)); // create a new scope for y and return x + y
</script>
<body>
Closures
</body>
</html>