JavaScript scope related content

Table of contents

1. Scope

1. Global scope

2. Local scope

3. The scope of variables

4. Global variables

5. Local variables

6. Summary

7. Scope chain

2. Pre-analysis

1. Variable pre-parsing

2. Function pre-parsing

3. Function expressions declare functions

4. Summary


1. Scope

Generally speaking, the name used in a piece of program code is not always valid and usable, and the code scope that limits the availability of this name is the scope of this name.

There are two scopes in JavaScript (before es6):

- Global scope.

- Local scope (function scope).

1. Global scope

Acts on the environment where all code is executed (inside the entire script tag) or a separate js file.

//js

var num = 10;//Global scope.

2. Local scope

The code environment acting on the function is the local scope. Because it is related to functions, it is also called function scope.

//js

function getnum(){ var num=20;}

JS does not have block scope.

In other programming languages ​​(such as java, c#, etc.), variables created in if statements and loop statements can only be used in this if statement and this loop statement, such as the following Java code:

  Java has block-level scope:

  ```java

  if(true){

    int number = 123;

    system.out.print(num);  // 123

  }

  system.out.print(num); // report an error

JavaScript code:

  if(true){

    var num = 123;

    console.log(num); //123

  }

  console.log(num );   //123

3. The scope of variables

In JavaScript, variables can be divided into two types according to different scopes: global variables and local variables.

4. Global variables

Variables declared in the global scope are called global variables (variables defined outside the function).

   function fun() {

            var num1 = 10; // num1 is a local variable that can only be used inside the function

            num2 = 20;

}

        fun();

 console.log(num2);//undefined

- Global variables can be used anywhere in the code.

- Variables declared with var in the global scope are global variables.

- In special cases, variables declared without using var in a function are also global variables (not recommended).

5. Local variables

Variables declared under the local scope are called local variables (variables defined inside the function).

- Local variables can only be used inside the function.

- A variable declared with var inside a function is a local variable.

- Function parameters are actually local variables.

6. Summary

Global variables: can be used anywhere, and will only be destroyed when the browser is closed, so it takes up more memory

Local variable: used only inside the function, it will be initialized when the code block where it is located is executed; it will be destroyed when the code block runs, thus saving more memory space

7. Scope chain

- As long as the code is in the same scope, it is written in the local scope inside the function, and it is in the global scope if it is not written inside any function;

- If there are functions in the function, another scope can be born in this scope;

- According to this mechanism in **[internal functions can access external function variables]**, chain search is used to determine which data can be accessed by internal functions, which is called scope chain.

  var num = 10;

  function fn() { // external function

       var num = 20;

        function fun() { // inner function

                console.log(num);//20

       }

            fun();

 }

fn();

practise:

 function f1() {

      var num = 123;

            function f2() {

                var num = 0;

                console.log(num); //??             }

            f2();

 }

 var num = 456;

 f1();

two:

 var a = 1;

        function fn1() {

            var a = 2;

            var b = '22';

            fn2();

            function fn2() {

                var a = 3;

                fn3();

                function fn3() {

                    var a = 4;

                    console.log(a); //value of a ?

                    console.log(b); //value of b?

                }

            }

        }

 fn1();

Summary: The scope chain adopts the principle of proximity to find the final value of the variable.

2. Pre-analysis

The concept of preparsing

- The js engine will promote all var and function in js to the front of the current scope.

- Variables declared by function are declared or defined in memory ahead of time.

- Code Execution: Execute JS statements from top to bottom.

1. Variable pre-parsing

Variable promotion (variable pre-parsing): The declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted.

console.log(num); //Directly print variable undeclared.

console.log(num); // undefined The variable declaration is not assigned a value.

var num = 10;

// Equivalent to executing the following code

// var num;

// console.log(num);

// num = 10;

Result: undefined

Note: Variable promotion only promotes declarations, not assignments.

2. Function pre-parsing

Function hoisting: The declaration of the function will be hoisted to the top of the current scope, but the function will not be called.

fn();

function fn() {

    console.log('print');

}

Result: console print string --- "print"

Note: The function declaration represents the whole function, so after the function is promoted, the function name represents the whole function, but the function is not called!

3. Function expressions declare functions

The function expression creates a function, which will perform variable promotion. At this time, the variable name of the receiving function cannot be called correctly:

fn();

var  fn = function() {

    console.log('Have I been executed');

}

Result: Error message "fn is not a function";

Explanation: Before this piece of code is executed, the variable declaration will be promoted, and the value of fn after promotion is undefined; while fn is called before fn is assigned to the function body, the value of fn is undefined at this time, so it cannot be called correctly.

4. Summary

- Our js engine runs js in two steps: pre-parsing code execution

- The pre-parsing js engine will promote all var and function in js to the front of the current scope

- Pre-parsing is divided into variable pre-parsing (variable promotion) and function pre-parsing (function promotion)

- Variable promotion is to promote all variable declarations to the front of the current scope without promoting assignment operations

- Function promotion is to promote all function declarations to the front of the current scope without calling the function.

Guess you like

Origin blog.csdn.net/qq_65715980/article/details/125562083