Hector and Coco
function hector() {
let spirit = "Remember Me"
return function() {
console.log(spirit);
}
}
let coco = hector();
// 💀 Hector is dead.
coco();
coco = null;
// 🗑️ Hector's spirit will be collected.
Closure examples
function delayLog(message, time) {
setTimeout(function() {
console.log(message);
}, time);
}
delayLog("Remember this!", 1000);
function compose (f, g) {
return function (x) {
return f(g(x));
}
}
const addOne = x => x + 1;
const double = x => x * 2;
const addOneThenDouble = compose(double, addOne);
console.log(
addOneThenDouble(3)
);
// 8
Lexical scope
const globalVar = "global";
function outer(outerParam) {
const outerVar = "outerVar";
function inner(innerParam) {
const innerVar = "innerVar";
console.log(globalVar); // ✅ global
console.log(outerVar); // ✅ outerVar
console.log(outerParam); // ✅ outerParam
console.log(innerVar); // ✅ innerVar
console.log(innerParam); // ✅ innerParam
}
return inner;
}
const innerOut = outer("outerParam");
innerOut("innerParam");
console.log(typeof outerVar); // 🚫 undefined
console.log(typeof innerVar); // 🚫 undefined
Counter with class
class Counter {
constructor(addValue) {
this.count = 0;
this.addValue = addValue;
}
increment() {
this.count += this.addValue;
console.log(this.count);
}
}
const counterBy1 = new Counter(1);
const counterBy3 = new Counter(3);
// Repeat below
counterBy1.increment();
counterBy3.increment();
Counter with closure
function createCounter(addValue) {
let count = 0;
return function() {
count += addValue;
console.log(count);
}
}
const counterBy1 = createCounter(1);
const counterBy3 = createCounter(3);
// Repeat below
counterBy1();
counterBy3();
# Python version
def create_counter(add_value):
count = 0
def counter():
nonlocal count
count += add_value
print(count)
return counter
counter_by_1 = create_counter(1)
counter_by_3 = create_counter(3)
# Repeat below
counter_by_1()
counter_by_3()