Getting started with front-end JavaScript-day06

(Creating is not easy, thank you, your support is the biggest motivation for me to move forward, if it is helpful to you after reading it, please leave your footprints)

Table of contents

scope

local scope 

global scope 

scope chain 

JS Garbage Collection Mechanism 

1. What is garbage collection mechanism 

2. Memory life cycle 

3. Algorithm description

Closure 

variable hoisting 

Function advanced 

function promotion

function parameters 

Dynamic parameters

remaining parameters

arrow function 

basic grammar 

Arrow function parameters

arrow function this

destructuring assignment

array destructuring

object deconstruction

Traverse the array forEach method 


scope

The scope (scope) specifies the "scope" in which the variable can be accessed, and the variable cannot be accessed without this "scope".
The scope is divided into:
        local scope
        global scope

local scope 

Local scope is divided into function scope and block scope.

1. Function scope:

Variables declared inside a function can only be accessed inside the function, and cannot be directly accessed outside.
Summarize:
1. Variables declared inside the function cannot be accessed outside the function
2. The parameters of the function are also local variables inside the function
3. Variables declared inside different functions cannot access each other
4. After the function is executed, the variables inside the function are actually cleared

2. Block scope: 

The code wrapped with { } in JavaScript is called a code block, and the variables declared inside the code block will [ possibly ] be inaccessible outside.
Summarize:
1. Variables declared by let will have block scope, but var will not have block scope
2. Constants declared with const also have block scope
3. Variables between different code blocks cannot access each other
4. It is recommended to use let or const

global scope 

The [outermost layer] of the <script> tag and the .js file is the so-called global scope, and the variables declared here can also be accessed inside the function.
Variables declared in the global scope can be accessed by any other scope

Notice:
1. The properties dynamically added to the window object are also global by default, which is not recommended!
2. Variables declared without any keyword in the function are global variables, which is not recommended! ! !
3. Declare global variables as few as possible to prevent global variables from being polluted

scope chain 

The scope chain is essentially the underlying variable lookup mechanism .
When the function is executed, it will first look for variables in the scope of the current function
If the current scope cannot be found, the parent scope will be searched step by step until the global scope
Summarize:
1. The scope of the nested relationship is connected in series to form a scope chain
2. Find variables in the same scope chain according to the rules from small to large
3. The child scope can access the parent scope, but the parent scope cannot access the child scope

JS Garbage Collection Mechanism 

Learning purpose: to pave the way for closure
Learning path:
1. What is garbage collection mechanism
2. Memory life cycle
3. Algorithm description of garbage collection

1. What is garbage collection mechanism 

Garbage Collection (Garbage Collection) referred to as GC
The allocation and recovery of memory in JS is done automatically, and the memory will be automatically recovered by the garbage collector when it is not in use.
Because of the existence of the garbage collector, many people think that JS does not need to care too much about memory management.
But if we don't understand the memory management mechanism of JS, we are also very prone to memory leaks (memory cannot be reclaimed)
Memory that is no longer used and not released in time is called a memory leak

2. Memory life cycle 

The memory allocated in the JS environment generally has the following life cycle:
1. Memory allocation: When we declare variables, functions, and objects, the system will automatically allocate memory for them
2. Memory usage: read and write memory, that is, use variables, functions, etc.
3. Memory recovery: After use, garbage collection will automatically reclaim unused memory
4. Description:
Global variables are generally not recycled (turn off page recycling);
In general, the value of the local variable will be automatically recycled if it is not used.

3. Algorithm description

Differences in stack space allocation:
1. Stack (operating system): The operating system automatically allocates and releases function parameter values, local variables, etc., and puts basic data types in the stack.
2. Heap (operating system): Generally allocated and released by the programmer, if the programmer does not release it, it will be recovered by the garbage collection mechanism . Complex data types are placed on the heap.
Here are two common browser garbage collection algorithms : reference counting and mark-and-sweep

Closure 

Concept: a function bundles references to the surrounding state, and the inner function accesses the scope of its outer function
Simple understanding: closure = inner function + variable of outer function

 Closure function: close data, provide operations, and external variables can also be accessed inside the function

Closure application: realize the privateness of data
For example, we want to count the number of function calls, and once the function is called, ++

 

variable hoisting 

Variable promotion is a "strange" phenomenon in JavaScript that allows access to variables before they are declared (only exists in var declaration variables)
Notice:
1. When a variable is accessed without being declared, a syntax error will be reported
2. The variable is accessed before the var declaration, and the value of the variable is undefined
3. Variables declared by let/const do not have variable promotion
4. Variable hoisting occurs in the same scope
5. In actual development, it is recommended to declare and then access variables
illustrate:
JS beginners often spend a lot of time getting used to variable hoisting, and some unexpected bugs often appear. Because of this, ES6 introduces block-level scope, using let or const to declare variables, making code writing more standardized and humanized.

Function advanced 

function promotion

Function hoisting is similar to variable hoisting in that functions can be called before they are declared.

Summarize:
1. Function promotion can make function declaration and call more flexible
2. There is no promotion of function expressions
3. Function hoisting occurs in the same scope

function parameters 

Dynamic parameters

arguments is a built-in pseudo-array variable inside the function, which contains all the actual parameters passed in when calling the function

Summarize:
1. arguments is a pseudo-array that only exists in the function
2. The role of arguments is to dynamically obtain the actual parameters of the function
3. The passed actual parameters can be obtained sequentially through the for loop
<!-- 
    写一个求和函数
 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        function getSum()
        {
            let sum =0;
            for(let i = 0;i<arguments.length;i++)
            {
                sum+=arguments[i]
            }
            console.log(sum)
        }
        getSum(2,3,4)
    </script>
</body>
</html>

remaining parameters

Rest parameters allow us to represent a variable number of parameters as an array
1. ... is a syntax symbol, placed before the last function parameter, used to obtain redundant actual parameters
2. The remaining actual parameters obtained by ... are a true array
In development, it is recommended to use more remaining parameters.

arrow function 

Purpose: The purpose of introducing the arrow function is to write a shorter function and not bind this. The syntax of the arrow function is more concise than the function expression
Usage scenario: Arrow functions are more suitable for places where anonymous functions are originally required

basic grammar 

Grammar 1: Basic writing

Syntax 2: Only one parameter can omit parentheses

 Syntax 3: If the function body has only one line of code, it can be written on one line, and return the value directly without writing return

Syntax 4: A parenthesized function body returns an object literal expression

Arrow function parameters

1. Ordinary functions have arguments dynamic parameters
2. The arrow function has no arguments dynamic parameters, but there are remaining parameters..args

arrow function this

Before arrow functions, every new function defined the this value of the function according to how it was called , which was very annoying.
An arrow function does not create its own this , it only inherits this from the previous level of its scope chain.

destructuring assignment

array destructuring

Array destructuring is a concise syntax for quickly mass-assigning the cell values ​​of an array to a series of variables.
Basic syntax:
1. The [] on the left of the assignment operator = is used to declare variables in batches, and the cell values ​​of the array on the right will be assigned to the variables on the left
2. The order of the variables corresponds to the position of the array cell value, and the assignment operation is performed sequentially
When the variable has many units and few values:

 When the number of variables is greater than the number of cell values, the redundant variables will be assigned undefined

When there are fewer variables and more unit values:

Use the remaining parameters to solve the situation of fewer variables and more unit values

The remaining parameters return an array 

To prevent undefined from passing the unit value, you can set the default value: the  default value of the variable is allowed to be initialized, and the default value will only take effect when the unit value is undefined

 Import on demand, ignoring some return values:

Structures that support multidimensional arrays:

object deconstruction

1. Basic grammar:
1. The {} on the left side of the assignment operator = is used to declare variables in batches, and the attribute value of the object on the right side will be assigned to the variable on the left side
2. The value of the object property will be assigned to the variable with the same name as the property
3. Note that the destructured variable name does not conflict with the external variable name or an error will be reported
4. When no attribute consistent with the variable name can be found in the object, the variable value is undefined

Assign new variable names:

It is possible to extract variables from an object and modify the new variable names at the same time

The colon means "what value: to whom" 

Array object destructuring 

Multi-level object destructuring: 

Traverse the array forEach method 

The forEach() method is used to call each element of the array and pass the element to the callback function
Main usage scenario: traverse each element of the array

grammar:

Notice:
1. forEach mainly traverses the array
2. The current array element of the parameter must be written, and the index number is optional.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const arr = ['red','green','pink']
        arr.forEach(function(item,index)
        {
            document.write(item)
            document.write(index)
        })
    </script>
</body>
</html>

The console shows as:                           

 

Guess you like

Origin blog.csdn.net/weixin_73295475/article/details/131664470