“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

preface

At the beginning of the article, a brief introduction to the concept of scope, scope related knowledge can refer to lexical scope and dynamic scope

  • [[scope]]Each function has a hidden attribute when it is created[[scope]], which points to the one created when the function executesAO
  • VOVariable object: also known asAO, store variables, parameters, functions and other data needed in the function.VOContains an additional property that points to creating theVOThe function itself.
  • Scope chain:[[scope]]A collection of execution-time context objects stored in. This collection is linked in a chain called a scope chain.
  • Find variables: To find variables in that function, look down from the top of the function’s scope chain.

Scope in JavaScript

JavaScript has two types of scope:

  • Global scope
  • Local scope

All variables except those defined inside functions and {} are in global scope. ES6 provides block-level scopes. Local scopes currently include function scopes and block-level scopes.

Global scope

Variables defined in a global scope can be accessed from anywhere. There are generally the following global scopes:

  • The outermost function defined and variables defined outside the outermost function have global scope.
  • imply global: An undeclared variable that is directly assigned.
function func() {
    implyGlobalVar = 'global';
    var localVar = 'local'
}
func() / / execution
console.log(implyGlobalVar) // global
console.log(localVar)       // localVar is not defined
Copy the code

var a = b = 10; B also belongs to Imply Global

  • windowAll properties on theJavaScript,window == Global

The downside of global scope is that if both John and John define the same global variable in their own globals at the same time, variable overwriting can occur.

Local scope

In contrast to global scope, a variable in a local scope can only be accessed by the local scope that defines it.

  • Function scope

    Variables and functions in a function scope can only be accessed from within the function

    function foo() {
        var localVar = 'local'
        function localFunc() {
            console.log(local)
        }
        localFunc() // local
    }
    localFunc() / / an error
    Copy the code

    Scope is hierarchical, and internal functions can access variables in the scope of external functions, but not vice versa (scope chain).

    function foo() {
        var localInnerVar = 'localInner'
        function localFunc() {
            console.log(local)
        }
        localFunc() // localInner
    }
    Copy the code

    Note: fast statements (statements inside {}), such as if, while, etc., do not create new scopes.

    if (1) {
        var a = 10
    }
    console.log(a) / / 10
    Copy the code
  • Block-level scope

    ES6 added let and const to declare variables that can only be accessed within the scope of the specified block.

    • No variable promotion occurs
    console.log(b) // undefined
    console.log(a) // Uncaught ReferenceError: a is not defined
    let a = 'i am there'
    var b = 'i am here'
    Copy the code
    • Duplicate declarations are not allowed
    console.log(a) // Identifier 'a' has already been declared
    var a = 'the first'
    let a = 'the second'
    Copy the code
    • Common closure issues resolved

    When learning about closure problems, it’s easy to write code like the following

    var arr = [];
    for (var i = 0; i < 10; i++) {
        arr[i] = function() {
            console.log(i);
        }
    }
    arr[0] ()/ / 10
    Copy the code

    The final result is 10. Run through all arRs and find that the final result is 10.

    We solved the closure problem by executing the function immediately:

    var arr = [];
    for (var i = 0; i < 10; i++) {
        (function (i) {
            arr[i] = function() {
                console.log(i);
            }
        }(i))
    }
    arr[0] ()/ / 0
    Copy the code

    Executing the function immediately to solve the closure problem above takes advantage of the knowledge of scope chains and adds a layer of scope to the outer layer of the ARR [I] function. But when we learn let, it is much easier to solve the above problems.

    var arr = [];
    for (let i = 0; i < 10; i++) {
        arr[i] = function() {
            console.log(i);
        }
    }
    arr[0] ()/ / 0
    Copy the code

3. Scope chain

When a JavaScript function is executed, it will first look for the corresponding attribute value in its OWN AO. If it cannot find it, it will look for it in the parent AO. If it cannot find it, it will look for it in the parent AO until it finds the root Window object.

Here is an example to simulate the flow of the entire scope chain:

function foo() {
    function bar() {
        var inner = 234;
        outer = 0;
        console.log(inner);
    }
    var outer = 123;
    bar();
    console.log(outer)
    console.log(glob)
}
var glob = 100;
foo()
Copy the code
  1. fooFunction creates

Global precompilation process to create GO

  1. fooFunction performs

Foo creates its own AO, precompiles tetralogy, and adds its AO to the top of the [[scope]] chain

  1. Bar function execution

Outer = 0; outer = 0; outer = 0; outer = 0; The inner attribute can be found in its own AO, so print 234 directly.

  1. barWhen the function completes,bartheAODestroy and continuefooThe unfinished code in

Outer can be found in its own AO, print 0 directly; The glob is not in its own AO and can be found in GO along the scope chain. Print 100. When foo completes execution, AO is destroyed.

Problem sets

Subject to a

var foo = 1;
function bar() {
    console.log(foo);  //undefined
    if(! foo) {var foo = 10;
    }
    console.log(foo); / / 10
}
bar();
Copy the code

Topic 2

var a = 1;
function b() {
    console.log(a);  // fn
    a = 10;
    return;
    function a() { }
}
b();
console.log(a); / / 1
Copy the code

The title three

console.log(foo); //fn C
var foo = "A";
console.log(foo)  //A
var foo = function () {
    console.log("B");
}
console.log(foo); //fn B
foo(); // B
function foo(){
    console.log("C");
}
console.log(foo)  //fn B
foo(); // B
Copy the code

The title four

var foo = 1;
function bar(a) {
    var a1 = a;
    var a = foo;
    function a() {
        console.log(a); //1
    }
    a1();
}
bar(3);
Copy the code

Past wonderful articles

  • Cow guest latest front-end JS written test 100 questions
  • The latest front end of the interview questions summary (including analysis)
  • Grab the latest front end test five hundred data analysis JS interview hot spots
  • Happy cat stroking for VSCode and website adoptive cats
  • [In memory of Mr. Qian] to achieve cool rocket launch effect
  • Native JavaScript soul torture (2), can you answer all correctly?
  • Native JavaScript soul Test (1), how much can you answer?
  • A thorough understanding of prototypes and prototype chains in JavaScript
  • Complete understanding of EventLoop in JavaScript
  • “2W word big chapter 38 interview questions” completely clear JS this pointing to the problem

After the language

Guys, if you find this article helpful, give a like to 👍 or follow ➕ to support me.

In addition, if this article has a question, or do not understand part of the article, you can reply to me in the comment section, we come to discuss, learn together, progress together!

If you feel confused in the comments section, you can also add my wechat or QQ for detailed communication, and the name is battlefield small bag.