What Is Missing From This Description For Nested Functions And Closures At Mozilla Developer Network?
Solution 1:
Closures are definitely a topic that is confusing at first, but really it boils down to this:
ANYTIME you have a nested function, you technically have a closure.
Just because you have a closure doesn't necessarily mean that your code will be affected in any significant way.
3. When a nested function relies on variables declared in a higher function (ancestor function) AND the nested function will have a lifetime that is LONGER than the function where those relied on variables were declared, you have a closure situation that needs understanding.
Those variables (used in the nested function, but declared in the higher order function, a.ka. free variables) cannot be garbage collected when the function in which they were declared completes because they are needed by the nested function which will outlive its parent/ancestor. This "outliving" can be caused by the nested function being returned to an even higher order caller by the nested function's parent or the nested function is assigned to another object (like a DOM object).
When this happens, a closure is created around the free variable and that variable's scope is now shared by any other in-memory function that relies on it as well. This causes a shared scope and is usually where confusion by a function that was supposed to get its own value does not. In those cases, modifying the inner function to receive a COPY of the ancestor's free variable can solve this confusion.
Post a Comment for "What Is Missing From This Description For Nested Functions And Closures At Mozilla Developer Network?"