Over how much of its enclosing scope does a (javascript) closure close?

后端 未结 2 401
失恋的感觉
失恋的感觉 2021-01-16 09:13

When I have some function that uses variables from its enclosing scope(s) and use that function outside of this scope (these scopes), then this is called a closure.

2条回答
  •  逝去的感伤
    2021-01-16 09:44

    The scope chain of a nested function contains references to activation objects of all outer functions whose execution resulted in definition of the nested function. These activation objects store ALL values in place when the outer function call returned and continue to exist because they are in a scope chain.

    So a closure, by definition, captures ALL variable values in scope. eval("typeof bigGuy"); within 'function () { /* CONTENTS */ } should demonstrate this.

    The ECMA standards probably* cover this (if you are writing a javascript engine and have the time). A solution may be to set large sized variables to undefined when their value is no longer required.


    *Based on reading ECMA 3.61 ten years ago. The computer science term "closure" did not appear in the standard. The production of closures has to be deduced by the reader as an implicit consequence of how nested function scope chains are constructed - which is in the standard. Scope chains comprise the currently executing function's activation object, outer functions' activation objects in reverse order, followed by the global object. The scope chain cannot be modified in user code.

提交回复
热议问题