JS Closure: The Function That Never Forgets

前端技术 Feb 22, 2024

JS Closure

Closure is when a function remembers where it was born, like how you remember your childhood home even after you moved out. In JavaScript, when an inner function references a variable from an outer function, that variable sticks around even after the outer function finishes running - because the inner function might need it later.

The classic example: a function that creates a "counter" with a private variable that only the returned function can access. This is the foundation of data encapsulation in JS.

Without closures, React hooks wouldn't work. Without closures, module patterns wouldn't work. Without closures, JavaScript would be a sad, flat language where everything forgets everything.

So next time someone asks "what is a closure", just say: it's JavaScript's way of saying "I got your back, bro" - keeping the variables you need alive even when the party is over.

Tags