Sub topic 3
Building Objects with Factory Functions
This chapter assumes you already know what a closure is and that closures capture variables rather than copies of their values. Here those ideas become practical patterns.
Factory Functions
A factory function is a function that returns a new object. When the object's methods close over a local variable, that variable becomes private state, and each call creates a separate copy of it.
function createAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const account = createAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefinedThe Module Pattern and IIFEs
An IIFE (immediately invoked function expression) is a function that runs once, as soon as it is defined. It returns a public interface and keeps everything else private. ES modules have mostly replaced this pattern, but you will still see it in older code.
const counterModule = (function () {
let count = 0;
function increment() {
count += 1;
return count;
}
return { increment };
})();
console.log(counterModule.increment()); // 1Callbacks, Timers, and Event Handlers
Callbacks often run long after the code that created them has finished. They still work because they close over the variables they use. They read those variables' current values when they run.
Partial Application, Currying, and Memoization
A returned function can remember an argument for later use:
function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10A closure can also hold a cache that lasts between calls and stays hidden from other code:
function memoize(fn) {
const cache = new Map();
return function (n) {
if (cache.has(n)) return cache.get(n);
const result = fn(n);
cache.set(n, result);
return result;
};
}
const square = memoize((n) => n * n);
console.log(square(4)); // 16, computed
console.log(square(4)); // 16, cachedClosures, this, and Arrow Functions
Arrow functions have no this of their own. They use the this of the function around them, so a callback written as an arrow function updates the right object:
function Timer() {
this.seconds = 0;
const id = setInterval(() => {
this.seconds += 1;
if (this.seconds === 3) {
clearInterval(id);
console.log('done:', this.seconds); // done: 3
}
}, 100);
}
new Timer();Memory Retention
Anything a live closure might still use cannot be garbage collected. A long-lived event handler that refers to a large array keeps the whole array in memory. To avoid this, copy only the value you need into a small variable:
function attachHandler(button) {
const bigData = new Array(1000000).fill('x');
const size = bigData.length;
button.addEventListener('click', () => {
console.log('Items:', size);
});
}Exercise
Two accounts are created with createAccount(10) and createAccount(20). After the first one calls deposit(5), what does the second one's getBalance() return, and why?
Show answer
It returns 20. Each call to createAccount creates its own balance variable, and each object's methods close over only their own copy.