JavaScript knowledge summary

catalogue

4, Process control content

1. Introduction to process control

2. Code block

(1) Branch structure - if statement

(2) Branch structure - if else statement

(3) Branch structure - if else if statement

(4) Branch structure - switch statement

(5) Loop statement - for loop

(5) Loop statement - double for loop

(6) Loop statement - while loop

(7) Loop statement - do - while loop

V array

1. Array introduction

2. Create array

3. Traversal array

The first traversal method is ordinary traversal

The second traversal method is for in

The third traversal method is for of

The fourth traversal method is the forEach() function

4. Other methods of array

(1) The push () method adds one or more elements to the end of the array and returns a new length.

(2)pop() method is used to delete the last element of the array and return the deleted element.

(3) The unshift () method adds one or more elements to the beginning of the array and returns a new length.

(4) the shift () method is used to delete the first element of the array and return the value of the first element.

(5)slice() method can extract a part of the string and return the extracted part with a new string. 

(6) The splice () method is used to add or remove elements from the array.

        (7) The concat () method is used to connect two or more strings.

(8)indexOf() queries the position of the element in the array

(9) LastIndexOf (element to query, actual position of query): query the position of the element in the array

(10)join(str) is used to join all elements in the array into a string

(11) reverse(): invert the array

(12) sort() is used to sort the array, which will also affect the original array

6, Function

1. Introduction of function

2. Use of functions

grammar

Parameters of function

Return value of function

The difference between break, continue and return

Use of arguments built-in object

Two ways to declare functions

call and apply

Arrow function

7, Scope

1. Scope introduction

(1) Global scope

(2) Local scope

2. Scope of variable

(1) Global variables: variables declared under the global scope are called global variables (variables defined outside the function).

(2) Local variables: variables declared under the local scope are called local variables (variables defined inside the function)

3. Scope chain

4. Pre analysis

7, Object

1. Object introduction

2. Use object

(1) Creating objects with literal values

(2) Create an object with new Object()

(3) Creating objects with constructors

3. Traversal object

4, Process control content

1. Introduction to process control

  • In the process of a program execution, the execution order of each code has a direct impact on the result of the program. Many times, we need to control the execution order of the code to realize the functions we want to complete.
  • Simple understanding: process control is to control the execution of code according to a certain structural order
  • There are three main structures of process control: sequence structure, branch structure and cycle structure
  • Sequential structure is to execute the code in sequence according to the sequence of the code
  • Branch structure is the code that executes different paths according to different conditions
  • The loop structure is based on conditions. If it is true, it will continue to execute the content, and if it is false, it will jump out

2. Code block

Use double curly braces {} in JavaScript to group code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
      Code block
          The same code block is either executed or not executed
          Variables declared with let in the code block cannot be accessed outside the code block
          var Declared variables can be accessed outside without scope
     */

    { // Internal variables of the first code block
        let a = 10;
        var b = 20;
        console.log(a);
    }
    console.log(b); // 20
    // console.log(a);  report errors

    { // Second code block
        let b = 30;
        console.log(b); // 30
    }

</script>
</body>
</html>

 

(1) Branch structure - if statement

Grammatical structure

// If the condition is true, execute the code, otherwise do nothing
if (Conditional expression) {
    // Code statement executed when the condition is satisfied
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
            By default, the code is executed line by line in top-down order
           Process control statement
            You can change the order of program execution
                Conditional judgment statement
                Conditional branch statement
                Circular statement

            Conditional judgment statement
               Syntax: if (conditional expression){
                    Statement body
               }
               Execution process: first evaluate and judge the conditional expression
                If true, the statement of the statement body will be executed, and if the result is false, it will not be executed

               Note: by default, the if statement will only control the following statements [in case {} is omitted]
     */

    if (true) {
        console.log("The body of the statement was executed")
    }
    let a = 10;

    if(a>0)
        console.log('a Greater than 10');
</script>
</body>
</html>

(2) Branch structure - if else statement

Grammatical structure

// If the condition holds, execute the code in if, otherwise execute the code in else
if (Conditional expression) {
    // [if] the condition is true, the code to be executed
} else {
    // [otherwise] executed code
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
            if - else sentence
     */
    let age = 60;

    // Judge whether the current age is retired, execute statement body 1 when the value is greater than or equal to 60, and execute statement body 2 when it is not satisfied
    if (age >= 60) { // Statement body 1
        console.log('You're retired');
    }else { // Statement body 2
        console.log('No retirement');
    }
    
</script>
</body>
</html>

(3) Branch structure - if else if statement

Grammatical structure

// Suitable for checking multiple conditions.
if (Conditional expression 1) {
    Statement 1;
} else if (Conditional expression 2)  {
    Statement 2;
} else if (Conditional expression 3)  {
   Statement 3;
 ....
} else {
    // None of the above conditions holds. Execute the code here
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
 
    /*
        if((expression){
            Statement body 1
          }else if((expression){
            Statement body 2
            }else{
                Statement body 3
            }
            if evaluates its conditional expression one time from the previous one
            If it is judged to be true, the statement body after the current if will be executed
            If the judgment result is false, continue to execute the downward else if until true is found
            If all judgment results are false, else statement will be executed

        After the code block is executed, other statements will not be executed
     */

    let score = 24;
    if (score >= 80) {
        console.log('excellent');
    }else if (score >= 60) {
        console.log('ordinary')
    }else {
        console.log('Bad');
    }
</script>
</body>
</html>

 

(4) Branch structure - switch statement

Grammatical structure

switch( expression ){ 
    case value1:
        // Code to execute when expression equals value1
        break;
    case value2:
        // Code to execute when expression equals value2
        break;
    default:
        // Code to be executed when the expression is not equal to any value
}


- keyword switch The following parentheses can be expressions or values, usually a variable

- keyword case , An expression or value followed by an option, followed by a colon

- switch The value of the expression matches the value in the structure case Compare the values of 

- If there is a match congruence(===) ,Then with the case The associated code block is executed and encountered break Stop when, the whole switch End of statement code execution

- If all case If the value of both does not match the value of the expression, the default Code in

  **Note: Execution case If there is no statement in it break,Then proceed to the next step case The sentence inside.**
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        switch sentence:
        Syntax:
            switch(Conditional expression){
                case expression:
                    sentence;
                case expression:
                    sentence;
                default:
                       Do not match the executed statement;
            }
    
            Execution process:
                The conditional expression after switch will be compared with case from top to bottom
                If congruent, compare the case s down in turn
                If none of them are equal, execute the statement after default
        Display Chinese according to numbers
        1 -> one
        2 -> two
        3 -> three
     */
    let a = 1;
    switch (a){
        case 1:
            console.log('one');
            break;
        case 2:
            console.log('two');
            break;
        case 3:
            console.log('three');
            break;
        default:
            console.log('Your input is incorrect');
    }

</script>

</body>
</html>

 

(5) Loop statement - for loop

Grammatical structure

for(initialize variable; Conditional expression; Operation expression ){
    //Circulatory body
}

1. Execute the operation expression, and the first round ends.
2. At the beginning of the second round, execute the conditional expression directly (no longer initialize the variable). If it is true ,Execute the loop body statement, otherwise exit the loop.
3. Continue to execute the operation expression, and the second round ends.
4. The follow-up is consistent with the second round until the conditional expression is false, ending the whole process for Cycle.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
    for loop
    Syntax: for (initialization expression; condition expression; update expression){
            Circulatory body
        }

        Execution process:
            for When the loop is executed:
                ①First execute the initialization expression to initialize a variable
                ②Execute the conditional expression to judge whether the loop is executed
                    If false, the loop ends
                    If true, the loop body is executed
                The update expression is executed after the loop body is executed
                and so on
     */
    for (let i = 0; i < 10; i++) {
        console.log(i);
    }

    // The expression of the for loop can be omitted without writing, and the loop is dead
    // for (; ;) {
    // }

</script>

</body>
</html>

 

(5) Loop statement - double for loop

Loop nesting refers to defining the syntax structure of a loop statement in a loop statement. For example, a for loop can be nested in a for loop statement. Such a for loop statement is called double for loop.

Grammatical structure

for (Initial of external circulation; Conditions of external circulation; Operation expression of outer loop) {
    for (Initial of internal circulation; Conditions of internal circulation; Inner loop operation expression) {  
       Code to execute;
   }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var star = '';
    for (var j = 1; j <= 3; j++) {
        for (var i = 1; i <= 3; i++) {
            star += '☆'
        }
        // Add a line break every time you have five stars
        star += '\n'
    }
    console.log(star);

</script>

</body>
</html>

(6) Loop statement - while loop

Grammatical structure

while (Conditional expression) {
    // Loop body code 
}

Implementation idea:

- 1 Execute the conditional expression first, if the result is true,Execute the loop body code; If yes false,Then exit the loop and execute the following code
- 2 Execute loop body code
- 3 After the loop body code is executed, the program will continue to judge the execution condition expression. If the condition is still true,The loop body will continue to execute until the loop condition is false The whole cycle will not end until
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

    /*
    while sentence
        while(Conditional expression){
                Circulatory body
                }
         Execution process: when the while statement is executed, the conditional expression will be evaluated and judged first
                If the statement is false, the statement ends
                If the statement is true, execute the statement body, and continue to judge the conditional expression after execution



 */

    // Three prerequisites for a cycle
    let i = 0; // Initialize variables to control the execution of the loop
    while (i < 3) { // Conditional expression to set the condition of the loop
        document.write("it's a nice day today<br>");
        i++; //Update expression
    }

    // When the conditional expression is always true, the loop body is always executed, which is called an dead loop
    while (true) {
        console.log('true');
    }
</script>
</body>
</html>

 

(7) Loop statement - do - while loop

Grammatical structure

do {
    // Loop body code - repeats the loop body code when the conditional expression is true
} while(Conditional expression);

Implementation ideas

- 1 Execute the loop body code once first 

- 2 Then execute the conditional expression. If the result is true,Then continue to execute the loop body code. If yes false,Then exit the loop and continue to execute the following code	

  Note: execute the loop body first, and then judge, do...while The loop statement executes the loop body code at least once
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        do while loop
           Syntax: do{
                Circulatory body
               }while(Expression);
            Execution process: when a do while loop is executed, the loop body will be executed first, and the conditional expression will be evaluated and judged after execution
            If false, the statement ends. If true, the loop body continues to execute
            And so on
     */

    let i = 0;
    do {
        console.log(i);
        i++;

    } while (i < 3)


</script>
</body>
</html>

 

V array

1. Array introduction

  • An array is a collection of data, each of which is called an element. Any type of element can be stored in the array.

2. Create array

There are two ways JavaScript can create arrays

Any type of data can be stored in the array, such as string, number, Boolean value, etc.

  1. Create an array with new
let Array name = new Array();
let array = new Array();

     2. Creating arrays using array literals

// 1. Create an empty array using array literal

let Array name = [];
// 2. Create an array with initial values using the array cotton method
let Array name = [1,2,3,4,5];
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
       array literal 
            You can create an array with brackets, which is consistent with the array object created by new Array()
            You can add array elements when creating an array

            Arrays can store any data type

            When using arrays, we ensure that the data types are consistent
     */
    let array = [10,20,30,40,50]; //  Similar to array = new Array();
    console.log(array); // [10, 20, 30, 40, 50]

    let array2 = new Array(20,20,30,40,50);
    console.log(array2); //  [20, 20, 30, 40, 50]

    let array3 = new Array(10);// Passing an array means creating an array with a length of 10
    console.log(array3.length); // 10

    for (let i = 0; i < array.length; i++) {
        console.log(array[i]);
    }

    array = ['hello', 'world',{name : 'guan'}];
    console.log(array[2].name); // guan

    // If the elements in an array are still arrays, the array is called a two-dimensional array
    array = [[1, 2, 3], [4, 5, 6]];

    console.log(array); // [Array(3), Array(3)]

</script>
</body>
</html>

 

3. Traversal array

The first traversal method is ordinary traversal

<script>
    let arr = [1, 2, 3, 4, 5, 6];

    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }

</script>

The second traversal method is for in

<script>
    let arr = [1, 2, 3, 4, 5, 6];

    // a is the index
    for(let i in arr){
        console.log(i,arr[i])
    }

</script>

The third traversal method is for of

<script>
    let arr = [1, 2, 3, 4, 5, 6];

    // Value is the value of the array
    for(let value of arr){
        console.log(value)
    }


</script>

The fourth traversal method is the forEach() function

<script>
    /*
     forEach() Traversal array
     This method requires a function as an argument
     The information of the element will be obtained by defining formal parameters
     forEach()The callback function of has three parameters
         1,The element currently being changed
         2,The index of the element currently traversed
         3,Array object currently being traversed
     */

    let arr = ['Lau Andy', 'Xue You Zhang', 'Liu Shishi', 'Da Chui Wang'];


    // The callback function of the forEach() function will be called multiple times, depending on how many elements there are
    arr.forEach(function (element,index,array) { // Functions defined by us and not called by us are called callback functions
        console.log(element,index,array);
    });
</script>

 

4. Other methods of array

(1) The push () method adds one or more elements to the end of the array and returns a new length.

[this method is destructive]

<script>
    let numbers = ["one", "two", "three", "four"];

   let res =  fruits.push("five");

    console.log(res,fruits);


</script>

(2)pop() method is used to delete the last element of the array and return the deleted element.

[this method is destructive]

<script>
    let numbers = ["one", "two", "three", "four"];

    let res = numbers.pop();

    console.log("result:", res);
    console.log("Array:", numbers);

</script>

(3) The unshift () method adds one or more elements to the beginning of the array and returns a new length.

[this method is destructive]

<script>
    let numbers = ["one", "two", "three", "four"];

    let res = numbers.unshift("newData");
    console.log("result:", res);

    console.log("array:", numbers);
</script>

(4) the shift () method is used to delete the first element of the array and return the value of the first element.

[this method is destructive]

<script>
    let numbers = ["one", "two", "three", "four"];

    let res = numbers.shift();
    console.log("result:", res);

    console.log("array:", numbers);
</script>

(5)slice() method can extract a part of the string and return the extracted part with a new string.

[non destructive]

Syntax: array slice(start, end)

Index starts at 0

<script>
    let arr = ['Sun WuKong', 'Zhu Bajie', 'Sand monk','Tang Monk'];

    /* slice() Slicing is a non-destructive method that does not affect the original array
        Used to intercept the array
        Parameter 1: index of intercepted starting position
        Contains the start position, not the end position
        Parameter 2: end position index of interception
        The second parameter can be omitted. If the second parameter is not written, it will be intercepted to the end
        Negative index values can be passed
     */
    let sliceArr= arr.slice(1, 3); 

    console.log(arr); // ['Monkey King', 'pig Bajie', 'sand monk', 'Tang Monk']
    console.log(sliceArr); // //['pig Bajie', 'sand monk']
    
    let newArr2 = arr.slice(1);
    console.log(newArr2); // ['pig Bajie', 'sand monk', 'Tang Monk']

    newArr2 = arr.slice(1, -1);
    console.log(newArr2); // ['pig Bajie', 'sand monk']
</script>

 

(6) The splice () method is used to add or remove elements from the array.

Syntax: array splice(index,howmany,item1,.....,itemX)

[destructive]

<script>
    /**
     *  splice(The starting position and number of deleted elements) can be used to delete, replace and add elements in the array
     *      Destructive methods
     *      Affect the original array
     *      Return value: deleted element
     *      3,Multiple parameters can be passed,
     *
     */
   let  arr1 = ['Sun WuKong', 'Zhu Bajie', 'Sand monk','Tang Monk'];
   // Delete elements of array
    let result = arr1.splice(0, 2);
    console.log(result); // ['Monkey King', 'pig eight commandments'] includes the starting position, excluding the ending position
    console.log(arr1);// ['sand monk', 'Tang Monk']

    let  arr2 = ['Sun WuKong', 'Zhu Bajie', 'Sand monk','Tang Monk'];

    // Replace elements of array
    result = arr2.splice(0, 2,'Ox demon king','Tang Monk');
    console.log(result); // ['Monkey King', 'pig eight commandments'] includes the starting position, excluding the ending position
    console.log(arr2); // ['ox demon king', 'Tang Monk', 'sand monk', 'Tang Monk']
</script>

 

(7) The concat () method is used to connect two or more strings.

[no destructiveness, return the spliced array as the return value]

<script>

    let arr = [1, 2, 3, 4];
    let arr2 = [5, 6, 7, 8];

    let concatArr = arr.concat(arr2);
    
    console.log(arr); //[1, 2, 3, 4]
    console.log(arr2);// [5, 6, 7, 8]
    
    console.log(concatArr); // [1, 2, 3, 4, 5, 6, 7, 8]
</script>

 

(8)indexOf() queries the position of the element in the array

<script>

    /*
     indexOf(Element to query, starting position of query)
         Query the position of the element in the array
         Index starts at 0
         Returns the position of the element in the first array
         If it does not exist, - 1 is returned
 */
    let array = ['Sun WuKong', 'Zhu Bajie', 'Sand monk'];

    let result = array.indexOf('Zhu Bajie');
    console.log(result); // 1

    result = array.indexOf('fucking great');
    console.log(result); // -1

</script>
</body>

 

(9) LastIndexOf (element to query, actual position of query): query the position of the element in the array

Return value: returns the position where the element last appeared

If not found, - 1 is returned

<script>

    let array = ['Sun WuKong', 'Zhu Bajie', 'Sand monk'];

    let index = array.lastIndexOf("Zhu Bajie");
    console.log('Indexes:',index);

    index = array.lastIndexOf("fucking great");
    console.log('Indexes:',index);


</script>

(10)join(str) is used to join all elements in the array into a string

str: specify a connector

Return value: string after splicing

<script>

    let array = ['Sun WuKong', 'Zhu Bajie', 'Sand monk'];

    let res = array.join(',');

    console.log('After splicing:', res);


</script>

(11) reverse(): invert the array

[destructive method]

<script>

    let array = ['Sun WuKong', 'Zhu Bajie', 'Sand monk'];

     array.reverse();

    console.log("array:", array); // ['monk Sha', 'pig Bajie', 'Monkey King']

    array = [1, 2, 3];

    array.reverse();
    console.log("array:", array); // [3, 2, 1]



</script>

(12) sort() is used to sort the array, which will also affect the original array

[destructive]

<script>

    let numArr2 = [42, 52, 63, 1, 3, 5, 63, 62];
    console.log(numArr2); // [1, 3, 42, 5, 52, 62, 63, 63]

    numArr2.sort(function (a,b) {
        // return a - b; //  Ascending order
        return b - a; Descending order
    });

    console.log(numArr2); //  [63, 63, 62, 52, 42, 5, 3, 1]


</script>

 

6, Function

1. Introduction of function

Function: encapsulates a code block that can be repeatedly called and executed. Through this code block, a large amount of code can be reused.

2. Use of functions

grammar

<script>
    // Function is the keyword that declares the function and must be lowercase
    // Since functions are generally defined to implement a function, we usually name the function as a verb, such as getSum
    function Function name(){
        // Function body
    }

//Call function
 Function name();
</script>

Parameters of function

  • Formal parameter: set when the function is defined, and pass in when receiving the call

  • Argument: real data passed in parentheses during function call

Syntax:

// Function declaration with arguments
function Function name(Formal parameter 1, Formal parameter 2 , Formal parameter 3...) { // You can define as many parameters as you want, separated by commas
  // Function body
}
// Function call with parameters
 Function name(Argument 1, Argument 2, Argument 3...); 

Details: when the number of formal parameters and arguments does not match

1. The number of arguments is equal to the number of formal parameters: output the correct result

2. The number of arguments is more than the number of formal parameters: only the number of formal parameters is obtained

3. The number of arguments is less than the number of formal parameters: multiple formal parameters are defined as undefined, and the result is NaN

In JavaScript, the default value of the formal parameter is undefined

Return value of function

After the function is executed, you can return the specified data through the return statement.

<script>

    // Declarative function
    function Function name (){
        ...
        return  The value to be returned;
    }

    // Call function
    Function name();    // At this point, you can call the function to get the value after return in the function body
</script>

Details: if there is no return, the returned value is undefined

The difference between break, continue and return

  • break: end the current loop body (e.g. for, while)

  • Continue: jump out of this cycle and continue to execute the next cycle (such as for and while)

  • Return: it can not only exit the loop, but also return the value in the return statement. At the same time, it can also end the code in the current function body

Use of arguments built-in object

  • When you are not sure how many parameters are passed, you can use arguments to get them.
  • In JavaScript, arguments is actually a built-in object of the current function. All functions have a built-in arguments object, which stores all the arguments passed.
  • arguments is displayed as a pseudo array, so it can be traversed. Pseudo arrays have the following characteristics:
    • With length attribute

    • Store data by index

    • Push, pop and other methods without array

      Note: this object is used inside the function to obtain the arguments passed during the function call.

<script>

    // Create a function to find the sum of any number
    function sum() {
        let res = 0;

        // Variable arguments
        for (let i = 0; i < arguments.length; i++) {

            res += arguments[i];
        }

        return res;
    }

    console.log(sum(12,  12)); // 12+12


    function fn() {
        /*
            In addition to this ☞ there is an implicit parameter in the function called arguments
            arguments Is a class array object (pseudo array)
               Class array objects and arrays operate in the same way
               You just can't call array methods

               When the function is executed, all arguments are stored in the arguments object
         */
        console.log(arguments.length) // 2
        console.log(arguments[0]); // hello
    };

    fn('hello','123');
</script>

 

Two ways to declare functions

1. Custom function mode

// Declaration definition method
function fn() {...}
// call  
fn();  

2. Anonymous function

// This is a function expression. Anonymous functions end with semicolons
let fn = function(){...};
// The function call must be written below the function body
fn();

call and apply

<script>

    function fn() {
        /**
         * The value of this is also different according to the calling method of our function
         *  1,Called as a function, this is window
         *  2,Called as a method, this is the object that calls the method
         *  3,Called with constructor, this is the new calling object
         */
        console.log(this); // Window
        console.log('Function executed')
    }

    fn();

    /*
        Method of function object
        call()
            When we call the call() method, the effect is actually similar to that of directly calling the function
            The difference is that this object is different
            call It can be used to specify the this of the function. The first parameter of the function is the one passed to this

         apply()The function is the same as call

         When calling a function through call and apply, who is the first formal parameter parameter and who is this
     */

    let obj = {};
    fn.call(obj);
    fn.apply();


    function fn1(a,b) {
        console.log(this);
        console.log(a,b);
    }
    // How call passes parameters
    fn1.call(window, 123, 456);

    // apply needs to put data in an array to pass parameters
    fn1.apply(window, [123, 456]);
</script>

 

Arrow function

The arrow function looks like a change in syntax, but it also affects the scope of this.

The arrow function does not bind this

<script>

    // Define common functions
    function fn(num) {
        return num + 2;
    }

    let res = fn(2); // 4
    console.log("Ordinary function result:", res); // Common function result: 4

    // Define arrow function
    let fn1 = (num) => num + 2;
    res = fn1(10);
    console.log("Arrow function result:", res); // Arrow function result: 12

    // If there are no parameters, it can be further simplified: if the return value has only one expression, curly braces can also be omitted:
    let fn2 =() => console.log('I'm an arrow function')
    fn2(); // I'm an arrow function

    //If there is only one parameter, parentheses can be omitted:
    let fn3 = num => num + 2;
    res = fn3(30);
    console.log("Arrow function result:", res); // Arrow function result: 32
</script>

7, Scope

1. Scope introduction

There are two scopes in JavaScript (before es6):

(1) Global scope

  • It acts as the environment for all code execution (inside the whole script tag) or a separate js file.

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

2. Scope of variable

In JavaScript, variables can be divided into two types according to different scopes:

(1) Global variables: variables declared under the global scope are called global variables (variables defined outside the function).

  • Global variables can be used anywhere in the code

  • The variables declared by var under the global scope are global variables

  • In special cases, variables that are not declared with var in the function are also global variables (not recommended)

(2) Local variables: variables declared under the local scope are called local variables (variables defined inside the function)

  • Local variables can only be used inside this function

  • The variables declared by var inside the function are local variables

  • The formal parameters of a function are actually local variables

be careful

  • Global variable: it can be used anywhere. It will be destroyed only when the browser is closed, so it takes up more memory

  • Local variable: only used inside the function. When the code block in which it is located is executed, it will be initialized; The contemporary code block will be destroyed after running, so it saves more memory space

3. Scope chain

  • As long as the code is in a scope, it is written in the local scope inside the function, and it is not written inside any function, that is, it is in the global scope;
  • 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], using chain search to determine which data can be accessed by internal functions is called scope chain.  
<script>
    function f1() { // Scope chain: use the proximity principle to find the final value of the variable
        var num = 123;
        function f2() {
            console.log( num );
        }
        f2();
    }
    var num = 456;
    f1(); // 123
</script>

4. Pre analysis

 

  • Javascript code is executed by the JavaScript parser in the browser.
  • The JavaScript parser runs JavaScript code in two steps: pre parsing and code execution.
  • Pre resolution:

    • Under the current scope, before JS code execution, the browser will declare or define variables with var and function declarations in memory by default. Pre parsing is also called variable and function promotion.

  • Code execution:

    • Execute JS statements from top to bottom.

      Note: pre parsing will complete the declaration of variables and functions before code execution.

<script>
    console.log(num);  // What's the result?
    var num = 10;      // undefined
    // Variable promotion only promotes the declaration, not the assignment
</script>

 

7, Object

1. Object introduction

  • In JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.
  • Objects are composed of properties and methods.
  • Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)

  • Method: the behavior of things is expressed by means in the object (commonly used verb)

For example, mobile phones

The size, color, weight, screen size and thickness of the mobile phone are the properties of the mobile phone

Making phone calls, sending text messages, playing games and smashing walnuts are all methods of mobile phones

  • The attribute name is set for each item of data in the object, which can access the data more semantically. The data structure is clear and the meaning is obvious, which is convenient for developers to use.

2. Use object

(1) Creating objects with literal values

  • You can use curly braces {} to create objects, which contain attributes and methods to express this specific thing (object); {} is expressed in the form of key value pairs
  • Key: equivalent to attribute name

  • Value: equivalent to attribute value and can be any type of value (numeric type, string type, boolean type, function type, etc.)

    <script>
        var people = {
            name: 'guan',
            age: 15,
            sex: 'male',
            sayHi: function () {
                console.log("Let's write code");
            }
        }
    
        console.log(people);
        // Use object: object name Attribute name
        console.log(people.age); // 15
        // The second method: object name [attribute name]
        console.log(people['age']); // 15
    
        // Method of using object: attribute name Key name ()
        people.sayHi();
    
    
    </script>

(2) Create an object with new Object()

<script>
   // Create an empty object
   let obj = new Object();

   // Add attributes and values to objects
   obj.name = 'guan';
   obj.age = 13;
   obj.sayHi = function () {
       console.log("We haven't written code yet");
   };

   console.log(obj.name);
   console.log(obj.age);

   obj.sayHi();
</script>

 

(3) Creating objects with constructors

  • Constructor: it is a special function, which is mainly used to initialize the object, that is, assign the initial value to the object member variable. It is always used together with the new operator. We can extract some public attributes and methods from the object and encapsulate them into this function.

  • Encapsulation format of constructor:

  • function Constructor name(Formal parameter 1,Formal parameter 2,Formal parameter 3) {
         this.Property name 1 = Parameter 1;
         this.Attribute name 2 = Parameter 2;
         this.Attribute name 3 = Parameter 3;
         this.Method name = Function body;
    }

    Call format of constructor

  • let obj = new Constructor name(Argument 1, argument 2, argument 3)

be careful:

  1. Constructor conventions are capitalized.

  2. this needs to be added in front of the properties and methods in the function to represent the properties and methods of the current object.

  3. return is not required in the constructor.

  4. When we create an object, we must call the constructor with new.

Function of new keyword

  1. Create an empty object before the constructor code starts executing;

  2. Modify the direction of this and point this to the created empty object;

  3. Code that executes the function

  4. After the function is completed, return this --- the created object

3. Traversal object

for (variable in Object name) {
    // Execute code here
}
<script>
   // Create an empty object
   let obj = new Object();

   // Add attributes and values to objects
   obj.name = 'guan';
   obj.age = 13;
   obj.sayHi = function () {
       console.log("We haven't written code yet");
   };
   for (let key in obj) {
       console.log(key, obj[key]);
   }
</script>

Keywords: Javascript ECMAScript

Added by Dark[NSF] on Sun, 20 Feb 2022 17:50:10 +0200