This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1e47327
commit f59082f
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
// Closure | ||
// A function with access to its own private variables | ||
|
||
// problem with global variables | ||
// var count = 0; | ||
|
||
// function countBirds() { | ||
// count += 1; | ||
// return count + ' bird'; | ||
// } | ||
|
||
// function countDogs() { | ||
// count += 1; | ||
// return count + ' dogs'; | ||
// } | ||
|
||
// function makeBirdCounter() { | ||
// var count = 0; | ||
// return function() { | ||
// count += 1; | ||
// return count + ' birds'; | ||
// } | ||
// } | ||
|
||
// function makeDogCounter() { | ||
// var count = 0; | ||
// return function() { | ||
// count += 1; | ||
// return count + ' dogs'; | ||
// } | ||
// } | ||
|
||
// Refactor | ||
function makeCounter(noun) { | ||
var count = 0; | ||
return function() { | ||
count += 1; | ||
return count + ' ' + noun; | ||
} | ||
} | ||
|
||
var birds = 3; | ||
|
||
// outer function | ||
function dogHouse() { | ||
var dogs = 8; | ||
|
||
// 1.0 | ||
// console.log(birds); // 3 | ||
// console.log(dogs); // 8 | ||
// This won't be avaliable outside the function | ||
|
||
// inner function | ||
function showDogs() { | ||
// inner function has access to outer function | ||
console.log(dogs); | ||
} | ||
return showDogs; | ||
} | ||
|
||
// 1.0 | ||
// console.log(birds); // 3 | ||
// console.log(dogs); // undefined | ||
|
||
var getDogs = dogHouse(); | ||
getDogs(); //8 |