Finished Module 1: Writing modular code with functions
parent
92c6071901
commit
95550ca928
@ -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
|
||||
```
|
Loading…
x
Reference in New Issue
Block a user