ES6 of JavaScript improvement class

Posted by The Stranger on Mon, 21 Feb 2022 11:53:22 +0100

A trip to the Empire??

content

address

Summary of JavaScript Foundation (I)??

https://blog.csdn.net/Augenstern_QXL/article/details/119249534

Function and scope of JavaScript Foundation (2)??

https://blog.csdn.net/Augenstern_QXL/article/details/119250991

JavaScript based objects and built-in objects (3)??

https://blog.csdn.net/Augenstern_QXL/article/details/119250137

Advanced DOM technology of JavaScript (4)??

https://blog.csdn.net/Augenstern_QXL/article/details/115416921

Advanced BOM technology of JavaScript (5)??

https://blog.csdn.net/Augenstern_QXL/article/details/115406408

Object oriented (VI) improvement of JavaScript??

https://blog.csdn.net/Augenstern_QXL/article/details/115219073

JavaScript improved ES6(7)??

https://blog.csdn.net/Augenstern_QXL/article/details/115344398

Catalog overview

1. Strict mode

  • In addition to providing normal mode, JavaScript also provides strict mode
  • The strict mode of ES5 is a way to adopt restrictive JavaScript variants, that is, to run JS code under strict conditions
  • Strict mode is only supported for browsers above IE10, and older browsers will be ignored
  • Strict mode makes some changes to the normal JavaScript semantics:
    • It eliminates some unreasonable and imprecise aspects of Javascript syntax and reduces some strange behaviors
    • Eliminate some unsafe places in code operation and ensure the safety of code operation
    • Improve the efficiency of the compiler and increase the running speed
    • Some grammars that may be defined in future versions of ECMAScript are disabled to pave the way for new versions of Javascript in the future. For example, some reserved words such as class, enum, export, extends, import and super cannot be used as variable names

1.1. Turn on strict mode

  • Strict mode can be applied to the whole script or individual functions.
  • Therefore, when using strict mode, we can divide it into two cases: script turns on strict mode and function turns on strict mode

1.1.2. Enable strict mode for script

  • To enable strict mode for the entire script file, you need to put a specific statement before all statements

  • 'use strict' or 'use strict'

Because "use strict" is quoted, older browsers will ignore it as a line of ordinary string.

Some scripts are basically in strict mode and some scripts are in normal mode, which is not conducive to file merging. Therefore, the whole script file can be placed in an anonymous function that is executed immediately. This creates a scope independently without affecting other script files.

<script>
	(function (){
    	'use strict';
    	 var num = 10;
    	 function fn() {}
	})();   
</script>

1.1.2. Turn on strict mode for function

  • To enable strict mode for a function, you need to put the "use strict" or "use strict" declaration before all statements in the function body

2. Changes in strict mode

  • Strict mode has made some changes to the syntax and behavior of JavaScript

2.1 variable regulation

  • In normal mode, if a variable is assigned without declaration, it is a global variable by default

  • Strict mode prohibits this usage. Variables must be declared with the var command before they are used

  • It is strictly forbidden to delete declared variables. For example, the ` ` delete x 'syntax is wrong

2.2. this pointing problem in strict mode

  1. Previously, this in the global scope function pointed to the window object

  2. In strict mode, this in the function in the global scope is undefined

  3. In the past, constructors can be called without adding new. When an ordinary function, this points to a global object

  4. In strict mode, if the constructor does not add a new call, this points to undefined. If you assign a value to it, an error will be reported

  5. The constructor instantiated by new points to the created object instance

  6. The timer this still points to window

  7. Event, object, or point to the caller

2.3 function change

  1. Functions cannot have arguments with duplicate names

  2. Functions must be declared at the top level, and the new version of JavaScript will introduce "block level scope" (introduced in ES6). In order to conform to the new version, it is not allowed to declare functions in non function code blocks

3. Higher order function

  • Higher order functions are functions that operate on other functions. They receive functions as parameters or output functions as return values

Receive function as parameter

<body>
    <div></div>
    <script>
        // Higher order functions - functions can be passed as parameters
        function fn(a, b, callback) {
            console.log(a + b);
            callback && callback();
        }
        fn(1, 2, function() {
            console.log('I was the last to call it.');

        });

    </script>
</body>

Function as return value

<script>
    function fn(){
        return function() {}
    }
</script>
  • At this point fn is a higher-order function
  • Function is also a data type, which can also be passed to another parameter as a parameter. The most typical is as a callback function
  • Similarly, functions can also be passed back as return values

4. Closure

4.1 variable scope

Variables are divided into two types according to the scope: global variables and local variables

  1. Global variables can be used inside functions
  2. Local variables cannot be used outside a function
  3. When the function is executed, the local variables in this scope will be destroyed.

4.2. What is closure

A closure is a function that has access to a variable in the scope of another function

Simple understanding: a scope can access local variables inside another function

<body>
    <script>
        // A closure is a function that has access to a variable in the scope of another function.
        // Closure: the scope of the function fn2 accesses the local variable num in another function fn1
        function fn1() {		// fn1 is the closure function
            var num = 10;
            function fn2() {
                console.log(num); 	//10
            }
            fn2();
        }
        fn1();
    </script>
</body>

4.3. Debug closure in chrome

  1. Open the browser and press F12 to start the chrome debugging tool.

  2. Set breakpoints.

  3. Find the Scope option (meaning Scope scope).

  4. When we refresh the page again, we will enter breakpoint debugging, and there will be two parameters in Scope (global Scope and local Scope).

  5. When fn2() is executed, there will be one more Closure parameter in the Scope, which indicates that closures have been generated.

4.4 function of closure

  • Extend the scope of the variable

4.5 closure exercise

4.5.1 click li to output the index number

<body>
    <ul class="nav">
        <li>Durian</li>
        <li>Stinky tofu</li>
        <li>Canned herring</li>
        <li>unfaithful man</li>
    </ul>
    <script>
        // Closure application - click li to output the index number of the current li
        // 1. We can add attributes dynamically
        var lis = document.querySelector('.nav').querySelectorAll('li');
        for (var i = 0; i < lis.length; i++) {
            lis[i].index = i;
            lis[i].onclick = function() {
                // console.log(i);
                console.log(this.index);

            }
        }
        // 2. Obtain the index number of the current small li by means of closure
        for (var i = 0; i < lis.length; i++) {
            // Four immediate execution functions are created using the for loop
            // The immediate execution function also becomes a small closure, because any function in the immediate execution function can use its i variable
            (function(i) {
                // console.log(i);
                lis[i].onclick = function() {
                    console.log(i);

                }
            })(i);
        }
    </script>
</body>

4.5.2 closure in timer

<body>
    <ul class="nav">
        <li>Durian</li>
        <li>Stinky tofu</li>
        <li>Canned herring</li>
        <li>unfaithful man</li>
    </ul>
    <script>
        // After closure application - 3 seconds, print the contents of all li elements
        var lis = document.querySelector('.nav').querySelectorAll('li');
        for (var i = 0; i < lis.length; i++) {
            (function(i) {
                setTimeout(function() {
                    console.log(lis[i].innerHTML);
                }, 3000)
            })(i);
        }
    </script>
</body>

5. Recursion

If a function can call itself internally, then the function is a recursive function

Simple understanding: the function calls itself internally. This function is a recursive function

Because recursion is prone to "stack overflow" errors, you must add an exit condition return

<body>
    <script>
        // Recursive function: the function calls itself internally. This function is a recursive function
        var num = 1;

        function fn() {
            console.log('I want to print six sentences');

            if (num == 6) {
                return; // Exit conditions must be added to recursion
            }
            num++;
            fn();
        }
        fn();
    </script>
</body>

6. Deep copy and shallow copy

  1. Shallow copy only copies one layer, and deeper object level only copies references
  2. Deep copy has multiple layers, and data at each level will be copied
  3. Object.assign(target,....sources) ES6 newly added method can be copied in shallow mode

6.1 shallow copy

// Shallow copy only copies one layer, and deeper object level only copies references
var obj = {
    id: 1,
    name: 'andy',
    msg: {
        age: 18
    }
};
var o = {}
for(var k in obj){
    // K is the attribute name and obj[k] is the attribute value
    o[k] = obj.[k];
}
console.log(o);
// Light copy grammar sugar
Object.assign(o,obj);

6.2. Deep copy

// Deep copy has multiple layers, and data at each level will be copied
var obj = {
    id: 1,
    name: 'andy',
    msg: {
        age: 18
    }
    color: ['pink','red']
};
var o = {};
// Encapsulation function
function deepCopy(newobj,oldobj){
    for(var k in oldobj){
        // Judge whether the attribute value belongs to simple data type or complex data type
        // 1. Get the attribute value oldobj[k]
        var item = obldobj[k];
        // 2. Judge whether the value is an array
        if(item instanceof Array){
            newobj[k] = [];
            deepCopy(newobj[k],item)
        }else if (item instanceof Object){
              // 3. Judge whether this value is an object
            newobj[k] = {};
            deepCopy(newobj[k],item)
        }else {
            // 4. It belongs to simple data type
            newobj[k] = item;
            
        } 
    }
}
deepCopy(o,obj);

7. Regular expression

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.

Regular table is usually used to retrieve and replace the text that conforms to a certain pattern (rule), such as verification form: the user name form can only enter English letters, numbers or underscores, and the nickname input box can enter Chinese (matching). In addition, regular expressions are often used to filter out some sensitive words in the page content (replacement), or get the specific part we want from the string (extraction), etc.

7.1. Features

  • Regular expressions are generally developed and copied directly
  • However, it is required to use regular expressions and modify them according to their actual situation

7.2. Creating regular expressions

In JavaScript, you can create regular expressions in two ways

  1. Created by calling the constructor of the RegExp object

  2. Create by literal

7.2.1. Create by calling the constructor of RegExp object

Created by calling the constructor of the RegExp object

var Variable name = new RegExp(/expression/);

7.2.2. Create by literal

Create by literal

var Variable name = /expression/;

An expression placed in the middle of a comment is a regular literal

7.2.3 test regular expression test

  • The test() regular object method is used to detect whether the string conforms to the rule. The object will return true or false, and its parameter is the test string

    regexObj.test(str)

  • regexObj writes regular expressions

  • str the text we want to test

  • Is to check whether the str text conforms to the regular expression specification we write

Examples

<body>
    <script>
        // Use of regular expressions in js

        // 1. Use RegExp object to create regular expression
        var regexp = new RegExp(/123/);
        console.log(regexp);

        // 2. Create regular expressions with literals
        var rg = /123/;
        // 3. The test method is used to check whether the string meets the specification required by the regular expression
        console.log(rg.test(123));
        console.log(rg.test('abc'));
    </script>
</body>

7.3 special characters in regular expressions

7.3.1 boundary symbol

The boundary character (position character) in regular expression is used to indicate the position of the character. There are mainly two characters

Boundary character

explain

^

Represents the text that matches the beginning of the line (starting with who)

$

Represents the text that matches the end of the line (with whom)

If ^ and $are together, it means that it must be an exact match

// Boundary character ^$
var rg = /abc/;   //Regular expressions don't need quotation marks, either numeric or string
// /abc / as long as abc is included, the string returns true
console.log(rg.test('abc'));
console.log(rg.test('abcd'));
console.log(rg.test('aabcd'));

var reg = /^abc/;
console.log(reg.test('abc'));   //true
console.log(reg.test('abcd'));	// true
console.log(reg.test('aabcd')); // false

var reg1 = /^abc$/
// It starts with abc and ends with abc. It must be abc

7.3.2 character class

  • Character class means that there are a series of characters to choose from, as long as you match one of them
  • All selectable characters are placed in square brackets

① [] square brackets

/[abc]/.test('andy');     // true

The following string returns true as long as it contains any character in abc

② [-] square bracket inner range character

/^[a-z]$/.test()

Add - inside the square brackets to indicate the range. Here, it means a - Z, and 26 English letters are OK

③ [^] inverse character inside square brackets^

/[^abc]/.test('andy')   // false

The addition of ^ inside square brackets indicates negation. As long as the characters in square brackets are included, false is returned

Pay attention to the difference from the boundary character ^ which is written outside the square brackets

④ Character combination

/[a-z1-9]/.test('andy')    // true

Character combinations can be used inside square brackets, which means that 26 English letters from a to z and numbers from 1 to 9 can be used

<body>
    <script>
        //var rg = /abc/;   As long as ABC is included 
        // Character class: [] indicates that there are a series of characters to choose from. Just match one of them
        var rg = /[abc]/; // It returns true as long as it contains a, b or c
        console.log(rg.test('andy'));
        console.log(rg.test('baby'));
        console.log(rg.test('color'));
        console.log(rg.test('red'));
        var rg1 = /^[abc]$/; // Choose one from three. Only the letters a, b or c return true
        console.log(rg1.test('aa'));
        console.log(rg1.test('a'));
        console.log(rg1.test('b'));
        console.log(rg1.test('c'));
        console.log(rg1.test('abc'));
        console.log('------------------');

        var reg = /^[a-z]$/; // 26 English letters. Any letter returns true - indicating the range from a to z  
        console.log(reg.test('a'));
        console.log(reg.test('z'));
        console.log(reg.test(1));
        console.log(reg.test('A'));
        // Character combination
        var reg1 = /^[a-zA-Z0-9_-]$/; // 26 English letters (both uppercase and lowercase) any letter returns true  
        console.log(reg1.test('a'));
        console.log(reg1.test('B'));
        console.log(reg1.test(8));
        console.log(reg1.test('-'));
        console.log(reg1.test('_'));
        console.log(reg1.test('!'));
        console.log('----------------');
        // If there is a ^ in brackets, it means to take the opposite meaning. Don't confuse it with our boundary symbol
        var reg2 = /^[^a-zA-Z0-9_-]$/;
        console.log(reg2.test('a'));
        console.log(reg2.test('B'));
        console.log(reg2.test(8));
        console.log(reg2.test('-'));
        console.log(reg2.test('_'));
        console.log(reg2.test('!'));
    </script>
</body>

7.3.3 quantifier

Quantifier is used to set the number of times a pattern appears

classifier

explain

*

Repeat zero or more times

Repeat one or more times

Repeat zero or once

{n}

Repeat n times

{n,}

Repeat n or more times

{n,m}

Repeat n to m times

<body>
    <script>
        // Quantifier: used to set the number of times a pattern appears
        // Simple understanding: how many times to repeat the following character a
        // var reg = /^a$/;


        //  *Equivalent to > = 0, it can appear 0 times or many times 
        // var reg = /^a*$/;
        // console.log(reg.test(''));
        // console.log(reg.test('a'));
        // console.log(reg.test('aaaa'));



        //  +Equivalent to > = 1, it can appear once or many times
        // var reg = /^a+$/;
        // console.log(reg.test('')); // false
        // console.log(reg.test('a')); // true
        // console.log(reg.test('aaaa')); // true

        //  ?   Equivalent to 1 | 0
        // var reg = /^a?$/;
        // console.log(reg.test('')); // true
        // console.log(reg.test('a')); // true
        // console.log(reg.test('aaaa')); // false

        //  {3} is repeated three times
        // var reg = /^a{3}$/;
        // console.log(reg.test('')); // false
        // console.log(reg.test('a')); // false
        // console.log(reg.test('aaaa')); // false
        // console.log(reg.test('aaa')); // true
        //  {3,} greater than or equal to 3
        var reg = /^a{3,}$/;
        console.log(reg.test('')); // false
        console.log(reg.test('a')); // false
        console.log(reg.test('aaaa')); // true
        console.log(reg.test('aaa')); // true
        //  {3,16} greater than or equal to 3 and less than or equal to 16
        var reg = /^a{3,6}$/;
        console.log(reg.test('')); // false
        console.log(reg.test('a')); // false
        console.log(reg.test('aaaa')); // true
        console.log(reg.test('aaa')); // true
        console.log(reg.test('aaaaaaa')); // false
    </script>
</body>

7.3.4 user name verification

Functional requirements:

  1. If the user name is valid, the following prompt message is: the user name is valid and the color is green
  2. If the user name input is illegal, the following prompt message is: the user name does not meet the specification, and the color is green

analysis:

  1. The user name can only be composed of English letters, numbers, underscores or dashes, and the length of the user name is 6 ~ 16 digits

  2. First, prepare the regular expression pattern / $[a-za-z0-9 -] {6,16}^/

  3. Validation begins when the form loses focus

  4. If it meets the regular specification, let the following span tag add the right class

  5. If it does not conform to the regular specification, let the following span tag add the wrong class

    enter one user name

7.4 summary in parentheses

  1. The inner side of the brace quantifier indicates the number of repetitions

  2. The bracketed character set matches any character in parentheses

  3. Parentheses indicate priority

    //The bracketed character set matches any character in parentheses
    var reg = /1 / ; / / a ∣ ∣ b ∣ ∣ c / / large Include number amount Words symbol in noodles surface show heavy complex second number v a r r e g = / a b c 3 /; // A | B | C / / the number of repetitions in the brace quantifier var reg = /^abc{3} /;// a ∣ b ∣ c / / the number of repetitions in the brace quantifier varreg=/abc3 /// It just makes c repeat abccc three times
    //Parentheses indicate priority
    var reg = /^(abc){3}$/; // It makes ABC repeat three times

Online test regular expression: https://c.runoob.com/

7.5 predefined classes

Predefined classes refer to shorthand for some common patterns

Scheduled class

explain

d

Match any number between 0-9, equivalent to [0-9]

D

Match all characters except 0-9, equivalent to [^ 0-9]

w

Match any letters, numbers and underscores, equivalent to [A-Za-z0-9_]

W

Characters other than all letters, numbers, and underscores are equivalent to [^ A-Za-z0-9_]

s

Match spaces (including line breaks, tabs, spaces, etc.), equivalent to []

S

Matches characters other than spaces, equivalent to [^]

7.5.1 form verification

analysis:

1. Mobile number: / ^ 1 [3 | 4 | 5 | 7 | 8] [0-9] {9}$/

2.QQ: [1-9][0-9]{4,} (Tencent QQ number starts from 10000)

3. The nickname is in Chinese: ^ [I-fu] {2,8}$

<body>
    <script>
        // Landline number verification: there are two formats of national landline number: 010-12345678 or 0530-1234567
        // Or symbol in regular|  
        // var reg = /^d{3}-d{8}|d{4}-d{7}$/;
        var reg = /^d{3,4}-d{7,8}$/;
    </script>
</body>

7.6 substitution in regular expressions

7.6.1 replace

The replace() method can replace a string, and the parameter used to replace can be a string or a regular expression

stringObject.replace(regexp/substr,replacement)
  1. The first parameter: the replaced string or regular expression

  2. Second parameter: replace with the string

  3. The return value is a new string after replacement

    //replace
    var str = 'andy and red';
    var newStr = str.replace('andy','baby');
    var newStr = str.replace(/andy/,'baby');

7.6.2 regular expression parameters

/expression/[switch]

There are three kinds of patterns for switch matching

  • g: Global matching
  • i: Ignore case
  • gi: global match + ignore case
  1. abc ↩︎

Topics: Javascript Front-end html Interview