[Web front-end basics | JS basics] scope

1-scope

1.1 Overview of scope

Generally speaking, the name used in a piece of program code is not always valid and usable, and the scope of the code that limits the availability of the name is the scope of the name. The use of scope improves the locality of program logic, enhances program reliability, and reduces name conflicts.

JavaScript(es6前)中的作用域有两种:
- 全局作用域
- 局部作用域(函数作用域)	

1.2 Global scope

It acts on all code execution environments (inside the entire script tag) or an independent js file.

1.3 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.

1.4 JS has no block-level scope

  • The block scope is covered by {}.

  • 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 loop statement, such as the following Java code:

    Java has a block-level scope:

    if(true){
          
          
      int num = 123;
      system.out.print(num);  // 123
    }
    system.out.print(num);    // 报错
    

    The above java code will report an error because {} in the code is a scope, and the declared variable num cannot be used outside of "{ }";

    And the similar JavaScript code will not report an error:

    There is no block-level scope in Js (before ES6)

    if(true){
          
          
      var num = 123;
      console.log(123); //123
    }
    console.log(123);   //123
    

2-Scope of variables

在JavaScript中,根据作用域的不同,变量可以分为两种:
- 全局变量
- 局部变量

2.1 Global variables

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

var num = 10;
console.log(num); //10
function fn() {
    
    
    console.log(num); //10
}
fn();
  • Global variables can be used anywhere in the code
  • Variables declared by var in the global scope are global variables
  • In special cases, variables declared without var in the function are also global variables (not recommended)

2.2 Local variables

Variables declared in the local scope are called local variables (variables defined inside a function)

function fn() {
    
    
    var num1 = 10;
    num2 = 20;
}
fn();
  • Local variables can only be used inside the function
  • Variables declared by var inside the function are local variables
  • The formal parameters of the function are actually local variables

2.3 The difference between global variables and local variables

  • Global variables: can be used in any place, only when the browser is closed will be destroyed, so it takes up more memory
  • Local variables: only used inside the function. When the code block is executed, it will be initialized; when the code block is finished, it will be destroyed, so it saves more memory space

3-scope chain

  • As long as it is code, there is at least one scope
  • Local scope written inside the function
  • If there are functions in the function, then another scope can be born in this scope
  • According to this mechanism that 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

Case study 1:

function f1() {
    
    
    var num = 123;
    function f2() {
    
    
        console.log( num );
    }
    f2();
}
var num = 456;
f1();

Scope chain: adopt the approach of the principle of proximity to find the final value of the variable. (The target looks outside)

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); //a的值 ?
            console.log(b); //b的值 ?
        }
    }
}
fn1();

4-pre-parse

4.1 Related concepts of pre-analysis

The JavaScript code is executed by the JavaScript parser in the browser. The JavaScript parser is
divided into two steps when running JavaScript code: pre-analysis and code execution.

  • Pre-parse: In the current scope, before the JS code is executed, the browser will declare or define the variables with var and function declarations in memory by default.

  • Code execution: JS statements are executed from top to bottom.

    Pre-analysis will execute the declaration of variables and functions before the code is executed.

4.2 Variable pre-analysis

Pre-analysis is also called variable and function promotion.
Variable promotion (variable pre-analysis): The variable declaration will be promoted to the top of the current scope, and the variable assignment will not be promoted.

console.log(num);  // 结果是多少?
var num = 10;      // ?
结果:undefined

注意:变量提升只提升声明,不提升赋值

4.3 Function pre-analysis

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

fn();
function fn() {
    
    
    console.log('打印');
}

Result: the console prints the string "print"

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

4.4 The problem of function expression declaration function

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

fn();
var  fn = function() {
    
    
    console.log('好好学习,天天向上');
}

Result: an error prompt "fn is not a function"

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

1

  • If it is to get the value, report an error
  • If it is an assignment, it becomes a global variable

Guess you like

Origin blog.csdn.net/qq_43490212/article/details/111433431