JavaScript Scope Chain, return and Closures Explained
The article explains how JavaScript looks up variables and how closures keep them alive. Each function call creates an execution context[1] with an outer pointer to the context around it. Variables are searched through these pointers up to the global context, and this lookup path is the scope chain[2]; it is set by where the code is written, not where the function is called. If a variable is not found, non-strict mode creates a global one, while strict mode throws an error.
Normally a function's context is destroyed when the function finishes. If a function defines an inner function and returns it, the inner function still references the outer variables, so they are kept; the article calls the inner function plus its captured variables a closure[3]. A closure forms when three conditions are met together: the functions are nested, the inner function is exposed to the outer scope, and it runs from outside.
Closures extend variable lifetimes and hide variables from direct outside access. The article warns that they can cause memory leaks, because captured variables are not reclaimed by garbage collection (GC)[4] while the closure is alive. Setting the function reference to null, such as addFn = null, lets the garbage collector free them.
Sources
-
CNJuejin ZH
理解 JavaScript 作用域链、return 与闭包


