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

后端 未结 2 400
失恋的感觉
失恋的感觉 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:28

    I'm mostly interested into whether there is some kind of specification for these cases

    The ECMAScript specification does not really detail this. It simply says that a function closes over the whole lexical environment which includes all variables in all parent scopes, organised in so-called environment records.

    Yet it does not specify how an implementation should do garbage-collection - so engines do have to optimise their closures themselves - and they typically do, when they can deduce that some "closed over" variable is never needed (referenced). Specifically, if you do use eval anywhere in the closure, they cannot do that of course, and have to retain everything.

    not so much about the behavior of some specific implementation

    Regardless, you'll want to have a look at How JavaScript closures are garbage collected, garbage collection with node.js, About closure, LexicalEnvironment and GC and How are closures and scopes represented at run time in JavaScript

提交回复
热议问题