From 95550ca928b5e1a31397edb1d9d044ce2531560c Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Wed, 12 May 2021 11:46:43 +1000 Subject: [PATCH] Finished Module 1: Writing modular code with functions --- 1_writing_modular_code_with_functions.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) 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