Thursday, June 23, 2022

Closure for javascript

In MDN web doc , A closure in JavaScript is defined as:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

The definition is not very clear as the closure involves both parent function and inner functions. So it needs more explanation about the definition:


When a (parent) function is executed, the function body will have all the local variables set to some value for the function execution. This execution environment including all the local variables is called parent function's lexical environment. 

If any inner function is defined within the parent function body, then the parent function's lexical environment will provide the variables defined in parent function, but referred by the inner function. Those variables are called closure variables.

The closure is created when the parent function is executed, and for each execution of parent function, a new closure environment is created. This makes sense, as each execution will have different variable values inside the parent function. All the inner functions defined in the parent function body, and whenever they are called, they will share the same lexical environment, i.e. the local variable's latest values declared in the parent function. 

So a closure is created when every time the parent function is executed, it captures all the local variables used by that execution instance. 

Note the closure only keeps the latest values of all the local variables defined in the parent function, so it the parent function does a for loop to update a local variable, then the local variable will have the latest value after the for loop finished. If a inner function is called later, then the inner function can only see the latest value of the parent function's closure variables, certainly the inner function can also update the closure variable to be visible to other inner functions. 

No comments:

Post a Comment