-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20-Closure.js
More file actions
28 lines (25 loc) · 898 Bytes
/
20-Closure.js
File metadata and controls
28 lines (25 loc) · 898 Bytes
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
/**
* Closure: means related to something, the lexical scope allows to access the variables statically of the outer scopes.
* There’s just one step until the closure!
*/
//Example:
function outerFunc() {
let outerVar = 'I am outside!';
function innerFunc() {
console.log(outerVar); // => logs "I am outside!"
}
innerFunc();
}
outerFunc();
// Note that innerFunc() invocation happens inside its lexical scope (the scope of outerFunc()).
// Let’s make a change: innerFunc() to be invoked outside of its lexical scope (outside of outerFunc()). Would innerFunc() still be able to access outerVar?
// Let’s make the adjustments to the code snippet:
function outerFunc() {
let outerVar = 'I am outside!';
function innerFunc() {
console.log(outerVar); // => logs "I am outside!"
}
return innerFunc;
}
const myInnerFunc = outerFunc();
myInnerFunc();