What are free variables?

前端 未结 3 1737
日久生厌
日久生厌 2020-12-13 13:28

Javascript closure definition says :

A \"closure\" is an expression (typically a function) that can have free variables together with an environment

3条回答
  •  春和景丽
    2020-12-13 14:11

    A "free-translation" could be: "out of scope" - variables.

    Since ECMAscript uses lexical scoping, a free variable is a variable which was defined in a parent-scope and gets looked-up by a scope-chain search.

    (function _outerScope() {
        var foo = 42;
    
        (function _innerScope() {
            var bar = 100;
    
            console.log( foo + bar ); // 142
        }());
    }());
    

    In the above example, foo is a free variable within the context of _innerScope. it becomes very obvious if we have a quick glance into the underlying concepts of ECMAscript.

    A Context is linked to an Activation Object (in ES3), respectively a Lexical Enviroment Record (in ES5), which contains things like: function declarations, variables declared with var and formal paramters, as well as a reference to all parent Activation Objects / Lexical Environments. If a variable needs to be accessed, the ECMAscript engine will first look into the AOs / LEs from the current Context itself; if it can't be found there, it looks into the parent AO's / LE's.

    Since any Context stores this data in an array-like structure (don't forget we're talking about implementation level here, not Javascript itself), we are talking about Lexical Scope, because we search through all parent Contexts in order.

提交回复
热议问题