|
1 | 1 | # Javascript Code samples
|
2 | 2 |
|
| 3 | +1. [Variable scope](#variable-scope) |
| 4 | +2. [Context](#context) |
| 5 | +3. [Closure](#closure) |
| 6 | + |
3 | 7 | ## Variable scope
|
4 | 8 |
|
5 | 9 | ### Global scope
|
@@ -110,3 +114,44 @@ var obj = {
|
110 | 114 | };
|
111 | 115 | obj.greet(); // Hello John Doe
|
112 | 116 | ```
|
| 117 | + |
| 118 | +## Closure |
| 119 | +### What is Closure? |
| 120 | + A Closure is created when an inner function tries to access the scope chain of its outer function meaning the variables outside of the immediate lexical scope. It means the inner function can access the outer function's variables. |
| 121 | + ``` |
| 122 | + function greet() { |
| 123 | + name = 'John Doe'; |
| 124 | + return function () { |
| 125 | + console.log('Hi ' + name); |
| 126 | + } |
| 127 | +} |
| 128 | +greetLetter = greet(); |
| 129 | +greetLetter(); // logs 'Hi John Doe' |
| 130 | +``` |
| 131 | + A closure can not only access the variables defined in its outer function but also the arguments of the outer function. |
| 132 | + ### Closure access outer scope |
| 133 | + Closures store references to the outer function's variables; they do not store the actual value. Closures get more interesting when the value of the outer function's variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables. |
| 134 | + ``` |
| 135 | + function userid () { |
| 136 | + var id = 999; |
| 137 | + // We are returning an object with some inner functions |
| 138 | + // All the inner functions have access to the outer function's variables |
| 139 | + return { |
| 140 | + getID: function () { |
| 141 | + // This inner function will return the UPDATED id variable |
| 142 | + // It will return the current value of id, even after the function changes it |
| 143 | + return id; |
| 144 | + }, |
| 145 | + setID: function (theNewID) { |
| 146 | + // This inner function will change the outer function's variable anytime |
| 147 | + id = theNewID; |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | +} |
| 152 | + |
| 153 | +var mjID = userid (); // At this juncture, the celebrityID outer function has returned. |
| 154 | +mjID.getID(); // 999 |
| 155 | +mjID.setID(567); // Changes the outer function's variable |
| 156 | +mjID.getID(); // 567: It returns the updated id variable |
| 157 | +``` |
0 commit comments