简体   繁体   中英

How javascript retains the outer function's execution context when an inner function is returned?

I'm reading these two blogs: execution context and scope chain published by David Shariff diving depth into javascript's execution context and scope chain concept.

One thing not clear to me after reading the above blogs is how javascript prevents a parent function's execution context being garbage collected?

Let's look at the following very simple code:

function outer(){
    var v1 = 'variable in outer function';

    function inner(){
        alert(v1);
    }

    return inner;
}

var innerFunc = outer();

When outer function is invoked, we get a pointer to the inner function. So at this stage, the inner function is created/defined, but not invoked yet.

According to the blogs, only when a function is being invoked, the scope chain will be established. So before the inner function is invoked, I think there's no pointer referencing to the outer function's execution context. Then how does js engine prevent the outer function's execution context being garbage collected?

The inner function has a reference to the context it was created in 1 . While the scope chain does not exist until the function is called, the scope chain is not what keeps the outer context alive.

1 or strictly speaking, there is some chain of references from the inner function to all closure variables it uses. It doesn't necessarily have to keep the entire context alive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM