diff --git a/1_writing_modular_code_with_functions.md b/1_writing_modular_code_with_functions.md index 612ffe0..6d831cd 100644 --- a/1_writing_modular_code_with_functions.md +++ b/1_writing_modular_code_with_functions.md @@ -118,7 +118,7 @@ where: ## How Closure Work -Local variable within function has short life span, as it's out of scope as function finish execution. But sometime we want to hold the variable (e.g. `counter` within function) +Local variable within function has short life span, as it's out of scope as function finish execution. But sometime we want to hold the variable (e.g. `counter` within function), we can use closure. e.g. w/o closure @@ -139,8 +139,25 @@ let greeting = (function() { let getMessage = function(){ return message; }; + // Use closure return { getMessage: getMessage, } -}) +})(); +console.log(greeting.getMessage()); // Hello +``` + +e.g. closure used for counter + +```javascript +function setupCounter(val){ + return function counter() { + return val++; + } +} +let counter1 = setupCounter(0); +console.log(counter1()); // 0 +console.log(counter1()); // 1 +let counter2 = setupCounter(10); +console.log(counter2()); // 10 ``` \ No newline at end of file