-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
53 lines (44 loc) · 1.59 KB
/
Copy pathscript.js
File metadata and controls
53 lines (44 loc) · 1.59 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
48
49
50
51
52
53
// Create a function which will hold another function.
function bankAccount() {
// Create two variables inside of the outer function.
// We will be accessing the two variables inside of our inner function.
const checking = 400;
let savings = 1000;
// Return a newly created inner function.
return {
displayFunds: function () {
// We have access to our outer functions variable which we console.log.
// This is a closure. The inner function has access to the outer functions scope.
savings++;
console.log(
`You have $${checking} in your checking account and $${savings} in your savings account`
);
},
};
}
// Create a new variable which holds the `bankAccount` function.
const myBank = bankAccount();
// With our newly created variable call the `displayFunds` method attached to it.
myBank.displayFunds();
// Check the console and expand the given object -> displayFunds -> Scope and then you should be able to visually see your closures.
console.dir(myBank);
// By console logging the outer function's variable we can see that the variables are not able to be accessed.
// console.log(checking);
// console.log(savings);
myBank.displayFunds();
myBank.displayFunds();
myBank.displayFunds();
myBank.displayFunds();
const myBank2 = bankAccount();
myBank2.displayFunds();
function counter() {
// Create a 'count' variable inside of the outer function.
let count = 0;
// Return an inner function creating a closure.
return {
increment: function () {
// Increment the outer function's 'count' variable by one.
return ++count;
},
};
}