In this Javascript Tutorial, we will learn how to create Inner Functions in java. Then we will study the concept of Closures and Inner Function returned by outer function. We will also study how Lexical Scope works with javascript closures. Finally we will create a self executing JavaScript function to have single Lexical Scoping.
Code Snippets
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 48 49 50 51 52 53 54 55 56 57 58 59 |
<!DOCTYPE HTML> <HTML> <HEAD > <TITLE>Learn Java Script</TITLE> <script type="text/javascript" > //Sample 01: Define a Closure for Counter function counter() { var count = 0; return function add1() { count = count + 1; return count; } } //Sample 04: Self Executing Function. //Creates a Closure with Single Lexical Scope var Global_Counter = (function GlobalCounter() { var count = 0; return function add1() { count = count + 1; return count; } })(); function print() { //Sample 02: Content of Closure //Where is count variable var Inc = counter(); document.writeln("Content of Inc is " + "<br/>"); document.writeln(Inc + "<br/>"); document.writeln("==========================<br/>"); //Sample 03: Closure with 2 Lexical Scopes var Inc2 = counter(); document.writeln("Inc Counter " + Inc() + "<br/>"); document.writeln("Inc2 Counter " + Inc2() + "<br/>"); document.writeln("Inc2 Counter " + Inc2() + "<br/>"); document.writeln("Inc2 Counter " + Inc2() + "<br/>"); document.writeln("Inc Counter " + Inc() + "<br/>"); document.writeln("==========================<br/>"); //Sample 05: Creates a Closure with Single Lexical Environment document.writeln("Inc Counter " + Global_Counter() + "<br/>"); document.writeln("Inc Counter " + Global_Counter() + "<br/>"); document.writeln("Inc Counter " + Global_Counter() + "<br/>"); document.writeln("==========================<br/>"); } </script> </HEAD> <BODY onload="print()"> <H1> JavaScript Closure Example </H1> <br/> </BODY> </HTML> |
Categories: JavaScript-Tube