JavaScript advanced tutorial (advanced functions, closures, regular expressions, ES6 new syntax, new extension methods)

catalogue

Function definition and call

Strict mode

What is strict mode

Turn on strict mode

Changes in strict mode

Higher order function

closure

regular expression

ES6 new syntax

Built in object extensions for ES6

Extension method of Array

Extension method of String

Set data structure

Function definition and call

Functions can be defined in three ways:

  • Custom function (named function)
function fn() {};
  • Function expression (anonymous function)
var fun = function() {};
  • new Function()
var fn = new Function('Parameter 1', 'Parameter 2', 'Function body')

This method is inefficient and inconvenient to write, so it is rarely used; All functions are instances (objects) of Function; Functions also belong to objects; Constructor;

There are many ways to call functions, including ordinary functions, object methods, constructors, bound event functions, timer functions, immediate execution functions, etc

fn(); // Ordinary function call
var o = {
  sayHi: function() {
     console.log('Leave now');
  }
};
o.sayHi(); // Method call of object
function Ename() {};
new Ename(); // Constructor mode
btn.onclick = function() {}; // Binding event function
setInterval(function() {}, 1000); // timer event 
(function() {
  console.log('Execute immediately');
})(); // Execute the function immediately and call it automatically

Strict mode

What is strict mode

Strict mode eliminates some irrationality and imprecision of JavaScript syntax and reduces some strange behaviors;

Eliminate some unsafe places of 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 the future version of ECMAScript are disabled to pave the way for the new version of JS in the future. For example, the reserved words class, enum, export, extends, import and super cannot be used as variable names

Turn on strict mode

The strict mode can be applied to the whole script or individual functions. Therefore, when using, the strict mode can be divided into two cases: script opening strict mode and function opening strict mode;

  • Turn strict mode on for scripts

To enable strict mode for the entire script file, you need to put a 'use strict' before all statements; (or "use strict"

<script>
    "use strict";
    // Next, write the normal js code and follow the strict pattern
</script>
  • Turn strict mode on for scripts

Some scripts are basically in strict mode, while others are in normal mode, which is not conducive to file merging. Therefore, the whole script file can be placed in an immediately executed anonymous function, so as to create a scope independently without affecting other script files;

<script>
        function fn() {
            "use strict";
            // Next, write the normal js code and follow the strict pattern
        }
</script>

Changes in strict mode

  • Variable specification

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 var command before use;

It is forbidden to delete declared variables, such as delete x; It's wrong

  • this pointing problem in strict mode

In the past, this in the global scope function points to the window object. In strict mode, this in the global scope function is undefined;

In the past, constructors can be called without new. When ordinary functions are called, this points to the global object. In strict mode, if constructors do not add new call, this will report an error;

  • Function change

Function cannot have parameters with duplicate names;

Function declaration must be at the top. Block level scope is introduced in ES6, and it is not allowed to declare functions in non function code blocks;

Higher order function

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

<script>
        function fn(callback) {
            callback && callback();
        }
        fn(function() {
            alert('hi')
        })
</script>

closure

Generally, variables are divided into two types according to different scopes: 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

Closures can access local variables inside another function from one scope;

Official statement: a closure refers to a function that has access to a variable in the scope of another function. A closure extends the scope of the variable;

regular expression

Regular Expression is a pattern used to match character combinations in strings. In Js, Regular Expression is also an object; It is usually used to retrieve and replace text that conforms to a certain pattern (rule), such as a verification form. 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;

Regular expression features:

  1. Flexibility, logic and functionality are very strong;
  2. It can quickly achieve the complex control of string in a very simple way;

Use of regular expressions:

  • Create regular expressions

In JS, you can create a regular expression in two ways,

1. Created by calling the constructor of the RegExp object

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

2. Create by literal

var Variable name = /expression/
  • 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 is the regular expression written, and str is the text to be tested
  • Composition of regular expressions

A regular expression can consist of simple characters, such as / abc /, or a combination of simple and special characters, such as / ab*c /. Special characters, also known as metacharacters, are special symbols with special significance in regular expressions, such as ^, $, + and so on. Special characters are divided into the following categories

1. Boundary character

The boundary character is used to indicate the position of the character. It mainly has two characters:

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

$indicates the text that matches the end of the line (with whom)

If the two are together, it means accurate matching;

2. Character class

Character class indicates that there are a series of characters to choose from, as long as one of them is matched, and all selectable characters are placed in square brackets;

[-]: - indicates the range, such as [a-z], indicating any character between a-z;

[^]: the inverse character ^ inside the square bracket indicates that it is not a character inside the square bracket;

3. Quantifier

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

*: indicates zero or more repetitions [0-n times];

+: indicates one or more repetitions [1-n times];

?: Represents zero or one repetition [0-1];

{n} : indicates n repetitions;

{n,}: indicates at least n repetitions;

{n,m}: represents n to m repetitions;

4. Bracket class

Braces are quantifiers, indicating the number of repetitions;

Brackets are character sets that match any character in the brackets;

Parentheses indicate priority;

5. Predefined classes

Predefined classes are shorthand for some common patterns:

Predefinedexplain
\dMatch any number between 0-9, equivalent to [0-9]
\DMatch all characters except 0-9, equivalent to [^ 0-9]
\wMatch any letters, numbers and underscores, equivalent to [A-Za-z0-9_]
\WMatches characters other than letters, numbers, and underscores, equivalent to [^ A-Za-z0-9_]
\sMatch spaces (including line breaks, tabs, spaces, etc.), equivalent to [\ t\r\n\v\f]
\SMatches characters other than spaces, equivalent to [^ \ t\r\n\v\f]
  • Substitution in regular expressions

1. Replace 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)

The first parameter is the replaced string or regular expression; The second parameter is the string replaced with; The return value is a new string after replacement;

However, the replace method can only replace the first string that meets the condition;

2. Regular expression modifier

/expression/[Modifier ]

The modifier indicates the matching pattern. It is written outside the regular expression and has three values:

  1. g means global match
  2. i means ignore case
  3. gi means global match + ignore case

For a detailed explanation of regular expressions, see the previous article: https://blog.csdn.net/ks795820/article/details/117279381?spm=1001.2014.3001.5501

ES6 new syntax

  • let

Variables declared by let are only valid at the block level (variables declared by let keyword have block level scope, and variables declared by var do not have block level scope); There is no variable promotion

  • const

const is used to declare a constant, which is the amount that the value (memory address) cannot change;

With block level scope;

Value must be assigned when declaring variables;

After variable assignment, the value cannot be modified;

  • Destructuring assignment

ES6 allows you to extract values from the array and assign values to variables according to their corresponding positions. Objects can also be deconstructed;

1. Array deconstruction

<div id="root">
        <div>How do you do</div>
    </div>
    <script>
        let [a, b, c] = [1, 2, 3];
        console.log(a); // 1
        console.log(b); // 2
        console.log(c); // 3
    </script>

If the deconstruction is unsuccessful, that is, the left and right sides do not correspond one by one, the variable value on the right is undefined

 <div id="root">
        <div>How do you do</div>
    </div>
    <script>
        let [a, b, c] = [1, 2];
        console.log(a); // 1
        console.log(b); // 2
        console.log(c); // undefined
    </script>

2. Object deconstruction

Similar to array deconstruction,

<div id="root">
        <div>How do you do</div>
    </div>
    <script>
        let person = {
            name: 'xiaoming',
            age: 20
        };
        let {
            name,
            age
        } = person;
        console.log(name); // xiaoming
        console.log(age); // 20
    </script>
  • Arrow function
() => { } // Formal parameters are placed in parentheses, and function bodies are placed in braces
 or
const fn = () => {}  // Usually, the arrow function can be assigned to a variable for later call

If the function body has only one sentence of code, and the execution result of the code is the return value of the function, the curly braces of the function body can be omitted;

<script>
        const sum = (n1, n2) => n1 + n2;
        const result = sum(10, 20);
        console.log(result); // 30
</script>

Similarly, if there is only one formal parameter, parentheses can also be omitted;

<script>
        const sum = n1 => n1;
        const result = sum(10);
        console.log(result); // 10
</script>

Note: the arrow function does not bind this keyword. This in the arrow function refers to the context this of the function definition position (that is, where the arrow function is defined, this will point to).

  • Residual parameters

The remaining parameters allow an indefinite number of parameters to be expressed as an array;

<script>
        function sum(first, ...args) {
            console.log(first); // 1
            console.log(args); // [2,3,4]
        }
        sum(1, 2, 3, 4);
</script>
<script>
        const sum = (...args) => {
            let total = 0;
            args.forEach(item => {
                total += item;
            })
            return total;
        };
        const sum1 = sum(1, 2, 3, 4);
        const sum2 = sum(1, 2);
        console.log(sum1); // 10
        console.log(sum2); // 3
</script>

The remaining parameters are used in conjunction with deconstruction:

<script>
        let students = ['Xiao Ming', 18, 'male'];
        let [s1, ...s2] = students;
        console.log(s1); // 'Xiao Ming'
        console.log(s2); // [18, 'male']
</script>

Built in object extensions for ES6

Extension method of Array

  • Extension operator (expand syntax)

The extension operator can convert an array or object into a comma separated sequence of parameters;

<script>
        let students = ['Xiao Ming', 18, 'male'];
        console.log(...students); // Xiaoming 18 male
</script>

Use here students later became Xiao Ming, 18, male, and then through the console The comma is removed after log;

The extension operator can be used to merge arrays;

<script>
        let students = ['Xiao Ming', 18, 'male'];
        let studentso = ['college student'];
        let studentsa = [...students, ...studentso]
        console.log(studentsa); // ['Xiao Ming', 18, 'male', 'college student']
</script>

The extension operator can also convert the traversable pseudo array into a real array, so as to use the method of array;

<script>
        let lis = document.getElementsByTagName('li');
        lis = [...lis];
</script>
  • Array.from()

This method converts the class array or traversable object into a real array;

<script>
        let arrayLike = {
            "0": 'a',
            "1": 'b',
            "2": 'c',
            length: 3
        };
        let lis = Array.from(arrayLike);
        console.log(lis); // ['a', 'b', 'c']
</script>

This method can also accept the second parameter, which is similar to the map method of array. It is used to process each element and put the processed value into the returned array;

 <script>
        let arrayLike = {
            "0": '1',
            "1": '1',
            "2": '1',
            length: 3
        };
        let lis = Array.from(arrayLike, item => item * 2);
        console.log(lis); // [2, 2, 2]
</script>

Extension method of String

  • Template string

Is the way to create a string, which is defined by backquotes:

 let name = `xiaoming`;

Variables can be parsed in the template string; Use ${}

<script>
        let name = `xiaoming`;
        console.log(name); //xiaoming
        let sayHello = `hello,my name is ${name}`;
        console.log(sayHello); // hello,my name is xiaoming
</script>

The function can be called in the template string;

<script>
        const sayHell = function() {
            return 'The new year is coming~';
        };
        let greet = `${sayHell()}`
        console.log(greet); // The new year is coming~
</script>

Set data structure

ES6 provides a new data structure Set, which is similar to array, but the values of members are unique and there are no duplicate values;

Set itself is a constructor used to generate set data structure;

const s = new Set();

The Set function can accept an array as a parameter for initialization;

const set = new Set([1,2,3]);
 <script>
        const data = new Set(['1', 1, '1', 'a', 'a'])
        console.log(data); // {'1', 1, 'a'} removed duplicate data
 </script>
  • Instance method of set data structure

add(value) is used to add a value and return the Set structure itself;

delete(value) is used to delete a value and return a Boolean value indicating whether the deletion is successful;

has(value) is used to test whether the value is a set member and return a Boolean value;

clear() is used to clear all set members without return value;

foreach() is the same as array, which is used to perform some operation on each member without return value;

  <script>
        const data = new Set(['1', 1, '1', 'a', 'a'])
        data.forEach(value => console.log(value)) // '1' 1 'a'
</script>

Keywords: Javascript Front-end TypeScript Algorithm

Added by BlackenedSky on Thu, 27 Jan 2022 03:48:00 +0200