2 ms·
I know you've already got a storm of replies, but I'd like to illustrate part of what I love about closure (especially when combined with anonymous objects like
by wwright 7y ago
I know you've already got a storm of replies, but I'd like to illustrate part of what I love about closure (especially when combined with anonymous objects like in JavaScript): you can replace classes, private vs public, "this", and other features with a simpler, smaller number of features.
const Counter = () => {
let counts = new Map();
return {
reset: () => {
counts = new Map();
},
count: (key) => {
const count = counts.get(key) + 1;
counts.set(key, count);
return count;
}
}
}
const items = ['apple', 'apple', 'banana', 'canteloupe'];
const counter = Counter()
items.forEach(item => {
console.log(item + ": count is", counter.count(item));
})
counter.reset();
// do some more counting now
IMO, this is much simpler [and prettier ;)] than the alternative using classes: you only need to know closures and objects, and the rules apply the same as they do in all other contexts. Classes in most languages usually come with their own twists and surprises.