当前位置:网站首页>JS deep understanding of scope

JS deep understanding of scope

2022-06-24 18:36:00 Brother Mengfan

Catalog

One 、 What is scope

Two 、 Scope

2.1、 Global scope

2.2、 Function scope

2.3、 Automatic global scope

3、 ... and 、 Scope internal principle

3.1、 Compile phase

​3.2、 Execution phase

3.3、 Query phase

3.4、 Nesting stage

 3.5、 Abnormal stage

Four 、 Lexical scope

5、 ... and 、 The shadowing effect


One 、 What is scope

Scope refers to the scope of a variable . Generally speaking , The names used in a piece of program code are not always valid and usable
Of , The scope of the code that defines the usability of the name is the scope of the name . The use of scopes improves program logic
The locality of , Enhance the reliability of the program , Reduced name conflicts .

stay JavaScript There are two scope types in :

(1) Global scope

(2) Function scope ( Local scope )

Two 、 Scope

2.1、 Global scope

Write directly in script In the tag JavaScript The code is global scope . When the page is opened, the global scope will automatically
Create , When the page closes, it is destroyed . There is a global in the global scope window Object can be used , And by
All objects with global scope will be used as window Object to use .
Example :
    <script>
        console.log(window);
        var a = 10;
        console.log(window.a);

        function aa() {
            console.log('aa')
        }
        window.aa();

        var aaa = {
            name: ' Zhang San '
        }
        console.log(window.aaa.name);
    </script>
Be careful : If this object / attribute / The method is window Of , So when using these objects / attribute / When the method is used , It can be omitted window Compiling .

2.2、 Function scope

Act on the code environment within the function , It's a local scope . Because it is related to functions , So it is also called function scope .
Local scope ( Function scope ) Is created when the function is called , After the function is executed, it is automatically destroyed . meanwhile , Every time
A single call to a function creates a new function scope , They are independent of each other .
The global scope can be accessed in the function scope , The function scope cannot be accessed in the global scope . When in the function scope
When using a variable in , It will first look in its own scope , If you find it, use it directly , If not found, it will go up
First level scope lookup , Until the global scope is found . If they are not found, an error will be reported .
Example :
    <script>
        var age = 18;

        function fn() {
            var age = 20;
            console.log(age); // 20
            console.log(this.age); // 18
            //console.log(this);
            console.log(window.age); // 18
        }
        window.fn();
    </script>

2.3、 Automatic global scope

If you assign a value to a variable that has not been declared , This variable will automatically become a global variable .
Example :
            function fn() {
                age = 19;
                console.log(age);
            }
            fn();
            console.log(window);
            console.log(age);
Be careful : If you do not specify... When defining a variable in a function var keyword , Then this variable will be automatically promoted to global operation
Use domain variables .

3、 ... and 、 Scope internal principle

The internal principles of the scope are divided into 5 Stages :
(1) Compile phase
(2) Execution phase
(3) Query phase
(4) Nesting stage
(5) Abnormal stage

3.1、 Compile phase

The process of compiling is that the compiler decomposes the program into lexical units , Parse lexical units into AST, And then AST To convert to a machine means Make , The process of waiting for execution .

3.2、 Execution phase

When the engine runs the code, it first looks for the current scope , see a Whether the variable is under the current scope , If it is , The engine will go straight
Take this variable ; If not , The engine will continue to look for the variable .
If the variable is found , Will be 2 Assign to the current variable , Otherwise the engine will throw an exception .
var a = 2; 
console.log(a);

3.3、 Query phase

When the variable is on the left side of the assignment operation, it is called LHS( Left query ) Inquire about , It is called when it appears on the right RHS( Right query ) Inquire about .
        var a = 2;// LSH  Inquire about  

        function add() {
            return 2;
        }

        var b = add(); // RHS  Inquire about 
The following is an example to analyze the query process :
        function fn(a) {
            console.log(a);
        }
        fn(1);
The query process :
(1)fn(): Would be right fn Function object RHS Inquire about ;
(2) Function arguments a = 1 , The variable a Conduct LSH Inquire about ;
(3)console.log(a): Yes console Object to carry out RHS Inquire about , And check if there is log() Method ;
(4)console.log(a): The variable a Conduct LHS quote , And pass the value of to log() Method .

3.4、 Nesting stage

The following is an example to illustrate the search mechanism for scope variables .

        function fn(a) {
            console.log(a + b);
        }
        var b = 2;
        fn(4);

 3.5、 Abnormal stage

        function fn(a) {
            a = b; // b is not defined 

        }
        fn(2);

        function fn2() {
            var b = 0;
            b(); // b is not a function 
        }
        fn2();

        function fn3() {
            a = 1;
        }
        fn(); //  If you do not execute this , Will be submitted to the  a is not defined

case analysis :

        function fn(a) {
            console.log(a);
        }
        fn(2);
First, the engine will respond to fn Conduct RHS Inquire about , Return to execute after finding , Then on a Conduct LHS Reference query , When you find it, put 2 Assign a value to it . And then to console Conduct RHS Reference query , because console It's a built-in object , Can successfully find , And then in console in RHS Reference query log() Method , When found, execute this method , Last RHS Reference query variables a, Because the function scope can find , Therefore, the RHS Reference query and output .

Four 、 Lexical scope

Lexical scope refers to all declared identifiers under the current scope .

      function fn(a) {
            var b = a * 2;

            function bar(c) {
                console.log(a, b, c);//2 4 12
            }
            bar(b * 3);
        }
        fn(2);

5、 ... and 、 The shadowing effect

Scope lookup starts with the innermost scope in which the runtime is located , Look up step by step , Until the first matching identifier is encountered
Until .
Identifiers with the same name can be defined in multiple nested scopes , This is called the masking effect .
    <script>
        var a = 0;

        function fn() {
            var a = 1;
            console.log(a);
        }
        fn();
    </script>
explain : From the above code run results, you can get : local variable a Obscures global variables a ( Or it is called overriding the global change
The amount ), This is called the masking effect .
原网站

版权声明
本文为[Brother Mengfan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211333166519.html