From c38c66a446287921eb466c863c8b1136d23ecc78 Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Wed, 12 May 2021 11:45:47 +1000 Subject: [PATCH] Module1: How Closures Work --- app.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/app.js b/app.js index 12e7f3d..6788a32 100644 --- a/app.js +++ b/app.js @@ -1,5 +1,12 @@ -let message = 'Hello'; -if (message === 'Hello') { - var count = 100; // var is within global scope, when it's not within object or function +function setupCounter(val) { + return function counter() { + return val++; + } } -console.log(count); // No reference error, which is dangerous \ No newline at end of file + +let counter1 = setupCounter(0); +console.log(counter1()); +console.log(counter1()); +let counter2 = setupCounter(10); +console.log(counter2()); +console.log(counter2()); \ No newline at end of file