4 ms·
You get a closure whenever you evaluate a function statement. When a statement containing the 'function' keyword is evaluated, you get a closure implicitly ins
by EdSharkey 10y ago
You get a closure whenever you evaluate a function statement. When a statement containing the 'function' keyword is evaluated, you get a closure implicitly instantiated for that new function instance.
Invoking an already existing function instance doesn't make a new closure - it keeps its existing one. Evaluating a statement containing the 'function' keyword does make a new closure.
A closure links to the enclosing function's scope, all the way back to the root/global scope (the window object on browsers).
Memory leaks can occur when closure scopes link infinitely, so it's handy to use the function-returns-function pattern (but not the way you described it) to 'reset' the closure links to something near the root scope.
JS module systems like CommonJS have done well to encourage very tidy closure scope chains even in extremely complex javascript programs.