From f59082fe1e5ea6cdc60421af3ec66f48ea2a9f1a Mon Sep 17 00:00:00 2001 From: Anthony Lee Date: Tue, 12 Sep 2017 09:50:26 -0500 Subject: [PATCH] Add simple closure example --- advance_js/closures.js | 66 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 advance_js/closures.js diff --git a/advance_js/closures.js b/advance_js/closures.js new file mode 100644 index 0000000..19e2a42 --- /dev/null +++ b/advance_js/closures.js @@ -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