How are closures and scopes represented at run time in JavaScript

后端 未结 2 746
眼角桃花
眼角桃花 2020-11-29 02:16

This is mostly an out-of-curiosity question. Consider the following functions

var closure ;
function f0() {
    var x = new BigObject() ;
    var y = 0 ;
           


        
2条回答
  •  抹茶落季
    2020-11-29 02:23

    In normal situations, local variables in a function are allocated on the stack -- and they "automatically" go away when the function returns. I believe many popular JavaScript engines run the interpreter (or JIT compiler) on a stack machine architecture so this obversation should be reasonably valid.

    Now if a variable is referred to in a closure (i.e. by a function defined locally that may be called later on), the "inside" function is assigned a "scope chain" that starts with the inner-most scope which is the function itself. The next scope is then the outer function (which contains the local variable accessed). The interpreter (or compiler) will create a "closure", essentially a piece of memory allocated on the heap (not the stack) that contains those variables in the scope.

    Therefore, if local variables are referred to in a closure, they are no longer allocated on the stack (which will make them go away when the function returns). They are allocated just like normal, long-lived variables, and the "scope" contains a pointer to each of them. The "scope-chain" of the inner function contains pointers to all these "scopes".

    Some engines optimize the scope chain by omitting variables that are shadowed (i.e. covered up by a local variable in an inner scope), so in your case only one BigObject remains, as long as the variable "x" is only accessed in the inner scope, and there are no "eval" calls in the outer scopes. Some engines "flatten" scope chains (I think V8 does that) for fast variable resolution -- something that can be done only if there are no "eval" calls in between (or no calls to functions that may do an implicit eval, e.g. setTimeout).

    I'd invite some JavaScript engine guru's to provide more juicy details than I can.

提交回复
热议问题