When we talk about closures and how they work, we’re actually discussing the relationship between functions and their execution contexts, and how these functions can remember and access variables from the scope in which they were created, even when they are called in a completely different scope.
var createCounter = function (init) {
let cur = init
return {
increment: () => ++cur,
decrement: () => --cur,
reset: () => (cur = init),
}
}Inside the createCounter Function
- Initialization Phase: When you call
createCounter(init), the JavaScript engine first creates a new execution context for this function call internally. This execution context contains a parameter namedinit, whose value is what you passed tocreateCounter. - Creating the
curVariable: Inside this execution context, thecurvariable is created and initialized to the value ofinit. At this point, bothcurandinitexist within the local scope ofcreateCounter. - Returning an Object: The
createCounterfunction returns an object containing three methods (increment,decrement,reset). Each method is a function that captures (closes over) its lexical scope at the time of definition, meaning they remember the values and environment ofcurandinit.
How Closures Work
- Formation of a Closure: After
createCounterhas executed and returned the object, according to conventional understanding, the local variables ofcreateCounter(curandinit) should be destroyed as the function execution is completed. However, since the methods in the returned object still referencecurandinit, these variables are not destroyed. Instead, they continue to exist so that these methods can use them when called in the future. This is the core characteristic of closures: functions remember and access the environment in which they were created. - Behavior of the Methods:
- The
incrementanddecrementmethods work by modifying the value of thecurvariable, increasing or decreasingcur’s value each time they are called. - The
resetmethod resets the value ofcurto the value ofinit, regardless of what theinitvalue was at the time of thecreateCountercall. Theresetmethod can access and use this initial value through the closure.
- The