Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7ff47d4

Browse files
authored
Added Closure
1 parent f10e3e6 commit 7ff47d4

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎README.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Javascript Code samples
22

3+
1. [Variable scope](#variable-scope)
4+
2. [Context](#context)
5+
3. [Closure](#closure)
6+
37
## Variable scope
48

59
### Global scope
@@ -110,3 +114,44 @@ var obj = {
110114
};
111115
obj.greet(); // Hello John Doe
112116
```
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /