ES6

let

        // Declare variables arbitrarily
        let a;
        let b, c, d;
        let e = 100;
        let f = 521, g = 'iloveyou', h = [];

        🍎1.Variables cannot be declared twicelet star = 'Lo Zhixiang';
        let star = 'pig'; // declared an error: Identifier 'star' has already been declared

        🍎2.Block level scoped global, function,eval
            if else while for 
        {
            let girl = 'Zhou Yangqing';
        }
        console.log(girl); //Uncaught ReferenceError: girl is not defined

        🍎3.There is no variable promotionconsole.log(song); //underfined
            let song = 'In love';

        🍎4.Does not affect the scope chain {let school = 'car';
            function fn() {
                console.log(school);  / / car
            }
            fn();
        }
Copy the code

const

        // Declare constants
        const SCHOOL = 'car';

        🍎1.Be sure to assign an initial valueconst A;  //Uncaught SyntaxError: Missing initializer in const declaration
        🍎2.Use uppercase for general constants (unspoken rule)const a = 100;
        🍎3.Constant values cannot be modified SCHOOL ='ATGUIGU';  //Uncaught TypeError: Assignment to constant variable. Constants cannot be assigned
        🍎4.Block level scope in {} {const PLAYER = 'UZI';
        }

        console.log(PLAYER);  //PLAYER is not defined
        🍎5.Element changes to arrays and objects do not count as changes to constantsconst TEAM = ['UZI'.'MXLG'.'Ming'.'Letme'];
        TEAM.push('Meiko');
        console.log(TEAM);//0: "UZI"1: "MXLG"2: "Ming"3: "Letme"4: "Meiko"
Copy the code

Deconstruction assignment

ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern known as deconstructed assignment.

🍎1. The array structure is used less

        const F4 = ['Little Shenyang'.'liu can'.'zhao four'.'Song Xiaobao'];
        let [xiao, liu, zhao, song] = F4;
        console.log(xiao);
        console.log(liu);
        console.log(zhao);
        console.log(song);
Copy the code

🍎2. Object deconstruction is commonly used

        const zhao = {
            name: 'Zhao Benshan'.age: 'not'.xiaopin: function () {
                console.log("I can do skits."); }};let { name, age, xiaopin } = zhao;
        console.log(name); / / zhao benshan
        console.log(age);  / / is unknown
        console.log(xiaopin);  //f(){console.log(" I can play a sketch "); }
        xiaopin(); // I can act in skits
Copy the code

🍎 3.

        let { xiaopin } = zhao;
        xiaopin();  //zhao is not defined
Copy the code

Template string

ES6 introduces new ways of declaring strings “” “” “

🍎 1. Statement

        let str = 'I'm a string too! `;
        console.log(str, typeof str);  // I am also a string. string
Copy the code

🍎2. Newline characters can be directly displayed in the content

        let str = ` < ul > < li > Shen Teng < / li > < li > Mary < / li > < li > wei zifeng < / li > < li > Allen < / li > < / ul > `;
        console.log(str); // If the original print is "" ", an error is reported
Copy the code

🍎3. Variable splicing ⭐

        let lovest = 'wei zifeng';
        let out = `${lovest}Is the funniest actor in my mind!! `; // Fixed format
        console.log(out); Wei Xiang is the funniest actor in my mind!!
Copy the code

Simplify object writing

🍎 Variables and functions, as properties and methods of objects. It’s much more concise

        // Declare two variables
        let name = 'car';
        let change = function () {
            console.log('We can change you!! ');
        }

        const school = {
            name,
            change,
            improve() {
                console.log("We can improve your skills."); }}console.log(school);/ / {name: "car", cahnge: f, improve, f}
Copy the code

Arrow function

The arrow function is suitable for callbacks unrelated to this. Timer, array method callback

Arrow functions are not suitable for callbacks related to this. DOM element event callback, object method

ES6 allows functions to be defined using arrows (=>).

Declare a functionlet fn = function () {}//
        
        let fn = (a, b) = > {
            return a + b;
        }
        // // Call function
        let result = fn(1.2);
        console.log(result); / / 3
Copy the code

🍎1. This is static. This always refers to the value of this in the scope in which the function was declared

         function getName() {
            console.log(this.name);
        }
        let getName2 = () = > {
            console.log(this.name);
        }

        // // Sets the name property of the window object
        window.name = 'car';
        const school = {
            name: "ATGUIGU"
        }

        // Direct calls direct calls to the window
        getName();//⭐ ordinary functions
        getName2();//⭐ arrow function car car

        // Call can change the internal value of the normal function this, but not the arrow function this⭐ common function getname.call (school);// ATGUIGU⭐ arrow function statically getName2.call(school);/ / car
Copy the code

🍎2. Cannot instantiate objects as constructors (ordinary functions can instantiate objects as constructors)

     let Person = (name, age) = > {
            this.name = name;
            this.age = age;
        }
        let me = new Person('xiao'.30);
        console.log(me);  //Person is not a constructor
Copy the code

🍎3. Arguments can’t be used (arguments can hold arguments, arrow functions can’t)

Arrow functionlet fn = () = > {
            console.log(arguments);
        }
        fn(1.2.3);//arguments is not definedCommon functionlet fn = function () {
            console.log(arguments);
        }
        fn(1.2.3);//Arguments(3) 0: 1 1: 2 2: 3
Copy the code

🍎4. Arrow functionshorthand

        //1) omit the parentheses when the parameter has one and only one
        let add = n= > {
            return n + n;
        }
        console.log(add(9));/ / 18
        
        //2) omit the curly braces. Return must be omitted when the code body contains only one statement
        // The result of the statement is the return value of the function
        let pow = n= > n * n;

        console.log(pow(8));/ / 64
Copy the code

case

        // requirement -1 when I click div 2s, the color becomes "pink"
        // Get the element
        let ad = document.getElementById('ad');
        // Bind events
        ad.addEventListener("click".function(){
            // Save this
            // let _this = this;
            / / timer
            setTimeout(() = > {
                // Change the background color this
                // console.log(this); Do not use arrow functions to point to the window
                // _this.style.background = 'pink';
                this.style.background = 'pink';// Arrow function this points to AD
            }, 2000);
        });

        // Requirement -2 returns an even number of elements from the array
        const arr = [1.6.9.10.100.25]; Common functionconst result = arr.filter(function (item) {
            if (item % 2= = =0) {
                return true;
            } else {
                return false; }}); Arrow functionconst result = arr.filter(item= > item % 2= = =0);

        console.log(result); / /,10,100 [6]
Copy the code

Function parametersThe default value

        //ES6 allows assigning initial values to function arguments
        🍎1.Parameter initial value A parameter with a default value, usually placed later (unspoken rule)function add(a, c = 10, b = 2) {
            return a + b + c;
        }
        let result = add(1.2);
        console.log(result);/ / 5
        
        
        🍎2.Combined with deconstruction assignmentfunction connect({ host = "127.0.0.1", username, password, port }) {
            console.log(host)  //atguigu.com
            console.log(username)  //root
            console.log(password)  //root
            console.log(port)  / / 3306
        }
        connect({
            host: 'atguigu.com'.username: 'root'.password: 'root'.port: 3306
        })
Copy the code

Rest parameters…

The rest argument is introduced to get arguments to functions instead of arguments

        // how ES5 gets arguments
        function date() {
            console.log(arguments); ⭐//arguments [' Baizhi ', 'Ajiao ',' Sihui ']
        }
        date(':'.'other'."Sophia");
Copy the code

🍎 rest parameters

        function date(. args) {
            console.log(args);//⭐[' Ajiao ', 'Baizhi ',' Sihui '] you can use filter some every map
        }
        date('other'.'cheung'."Sophia");
Copy the code

The 🍎rest parameter must be placed at the end of the parameter

        function fn(a, b, ... args) {
            console.log(a);/ / 1
            console.log(b);/ / 2
            console.log(args);/ / 3,4,5,6
        }
        fn(1.2.3.4.5.6);
Copy the code

Extended operators… Extended operators convert arrays into comma-separated sequences of arguments

        // Declare an array...
        const tfboys = [Jackson Yi.'hanah'.'Wang Junkai'];// < span style = "max-width: 100%; clear: both; min-height: 1em;

        // Declare a function
        function chunwan() {
            console.log(arguments);
        }

        chunwan(tfboys);// arguments(1) 0:(' yi yangqixi ',' wang yuan ',' wang junkai ')chunwan(... tfboys);// Arguments (3) 0:' Yi Yangqixi ',1:' Wang Yuan ',2:' Wang Junkai ')
Copy the code

case

🍎1. Array merge sentient accidentally killed Detective Tang

        const kuaizi = ['Wang Taili'."Xiao"];
        const fenghuang = ['chenrui'.'ling flowers'];
        // const zuixuanxiaopingguo = kuaizi.concat(fenghuang);
        const zuixuanxiaopingguo = [...kuaizi, ...fenghuang];
        console.log(zuixuanxiaopingguo);  //Array(4) 0: "Wang Tai Li" 1: "Xiao Yang" 2: "Zeng Yi" 3: "Ling Hua"
Copy the code

🍎2. Array cloning

        const sanzhihua = ['E'.'G'.'M'];
        const sanyecao = [...sanzhihua];
        console.log(sanyecao); // Array(3)['E','G','M']
Copy the code

🍎3. Convert the pseudo-array into a real array

        const divs = document.querySelectorAll('div');
        console.log(divs); //NodeList(3) 0: div 1: div 2: div
        const divArr = [...divs];
        console.log(divArr);// Array(3)0: div 1: div 2: div
Copy the code

Symbol

Creating a Symbol value is the only way to resolve naming conflicts

                        let s = Symbol(a);console.log(s, typeof s); //Symbol() 'symbol'Passing stringlet s2 = Symbol('car');
                        let s3 = Symbol('car');
                        console.log(s2 === s3);//false
        
                           Symbol. For creatinglet s4 = Symbol.for('car');
                        let s5 = Symbol.for('car');
                        console.log(s4 === s5);//true
        
        
                        // Cannot be computed with other data
                        let result = s + 100;
                        let result = s > 100;
                        let result = s + s;
         //Uncaught TypeError: Cannot convert a Symbol value to a number
Copy the code

The case adds methods to the object

Add the method up Down to the object

        let game = {
            name: tetris.up: function () {},down: function () {}};// Declare an object
        let methods = {
            up: Symbol(),
            down: Symbol()
        };

        game[methods.up] = function () {
            console.log("I can change shapes.");
        }

        game[methods.down] = function () {
            console.log("I can fall fast!!");
        }

        console.log(game);/ / {name: 'tetris' up: Ζ’, down: Ζ’, Symbol () : Ζ’, Symbol () : Ζ’}
Copy the code

    let youxi = {
            name: "Werewolf kill.".// Encapsulate method
            [Symbol('say')]: function () {
                console.log("I may speak.")},// Encapsulate method
            [Symbol('zibao')]: function () {
                console.log('I can blow myself up.'); }}console.log(youxi)//{name: 'werewolf ', Symbol(say): Ζ’, Symbol(zibao): Ζ’}
Copy the code

There are several built-in attributes that can be displayed in a particular scenario (added later for examples below)

        // 🍎 control type detection yourself
        class Person {
            static [Symbol.hasInstance](param) {
                console.log(param);//Object[[Prototype]]: Object
                console.log("I'm being used to detect types.");// I am used to detect the type
                return false; }}let o = {};

        console.log(o instanceof Person);//false
        // 🍎 whether array merge can be expanded
        const arr = [1.2.3];
        const arr2 = [4.5.6];
        arr2[Symbol.isConcatSpreadable] = false;
        console.log(arr.concat(arr2));
Copy the code

The iterator gets the data it wants

An interface that provides unified access to a variety of different data structures. Any data structure can be traversed by deploying the Iterator interface.

Iterator interface: Attributes in an object

Principle: When you need to customize traversal data

1) Create a pointer object that points to the start of the current data structure

2) The first time the object next method is called, the pointer automatically points to the first member of the data structure.

3) Keep calling the next method, moving the pointer back until it points to the last member

4) Each call to the next method returns an object containing the value and done attributes.

        // Declare an array
        const xiyou = ["Tang's monk.Sun Wukong.'Pig Eight Quit'.'沙僧'];

        / / used for... Of Traversal number group in Key name of key value
        for (let v of xiyou) {
            console.log(v);  // Tang Monk sun Wukong Pig Eight quit sand monk
        }
        
        
        let iterator = xiyou[Symbol.iterator]();

        // // calls the next method of the object
        console.log(iterator.next());//done false value
        console.log(iterator.next());/ /...
        console.log(iterator.next());
        console.log(iterator.next());
        console.log(iterator.next());//done false value
        // I am therefore underpaid done true
Copy the code

case

        // Declare an object
        const banji = {
            name: "Terminal Class".stus: [
                'xiaoming'.'xiaoning'.'xiaotian'.'knight'
            ],
            [Symbol.iterator]() {
                // Index variable
                let index = 0;
                //
                let _this = this;
                return {
                    next: function () {
                        if (index < _this.stus.length) {
                            const result = { value: _this.stus[index], done: false };
                            // subscript increment
                            index++;
                            // Return the result
                            return result;
                        } else {
                            return { value: undefined.done: true}; }}}; }}// Iterate over the object ⭐⭐⭐ to get the data I want
        for (let v of banji) {
            console.log(v);   //'xiaoming','xiaoning','xiaotian','knight'
        }
Copy the code

Generator asynchronous solution

A generator is simply a special function

Asynchronous programming pure callback functions node FS Ajax mongodb

The separator yield for the function code

        function* gen() {
            // console.log(111);
            yield 'One without an ear';
            // console.log(222);
            yield 'One without a tail';
            // console.log(333);
            yield 'That's strange';
            // console.log(444);
        }

        let iterator = gen();
        // The iterator object next prints the same as the iterator
        console.log(iterator.next());//Object done: false value: "δΈ€εͺζ²‘ζœ‰θ€³ζœ΅"
        console.log(iterator.next());
        console.log(iterator.next());
        console.log(iterator.next());

        // The output has no ears and the other has no tail
        for (let v of gen()) {
            console.log(v);
        }
Copy the code

Generator function parameters

        function* gen(arg) {
            console.log(arg);
            let one = yield 111;
            console.log(one);
            let two = yield 222;
            console.log(two);
            let three = yield 333;
            console.log(three);
        }

        // Perform the fetch iterator object
        let iterator = gen('AAA');
        console.log(iterator.next());
        // The next method can also pass in arguments as the first return result
        console.log(iterator.next('BBB'));
        console.log(iterator.next('CCC'));
        console.log(iterator.next('DDD'));
Copy the code

Generator function instance

Asynchronous programming file operations Network operations (Ajax, Request) database operations

After 1s, the console outputs 111, after 2s, 222, after 3s, 333

        // Call back to hell
        setTimeout(() = > {
            console.log(111);
            setTimeout(() = > {
                console.log(222);
                setTimeout(() = > {
                    console.log(333);
                }, 3000);
            }, 2000);
        }, 1000); 🍎 Another way to implementfunction one() {
            setTimeout(() = > {
                console.log(111);
                iterator.next();
            }, 1000)}function two() {
            setTimeout(() = > {
                console.log(222);
                iterator.next();
            }, 2000)}function three() {
            setTimeout(() = > {
                console.log(333);
                iterator.next();
            }, 3000)}function* gen() {
            yield one();
            yield two();
            yield three();
        }

        // Call the generator function
        let iterator = gen();
        iterator.next();
Copy the code

case

        // Get user data, order data, commodity data
        function getUsers() {
            setTimeout(() = > {
                let data = 'User data';
                // Call the next method and pass in the data
                iterator.next(data);
            }, 1000);
        }

        function getOrders() {
            setTimeout(() = > {
                let data = 'Order data';
                iterator.next(data);
            }, 1000)}function getGoods() {
            setTimeout(() = > {
                let data = 'Commodity data';
                iterator.next(data);
            }, 1000)}function * gen() {
            let users = yield getUsers();
            let orders = yield getOrders();
            let goods = yield getGoods();
        }

        // Call the generator function
        let iterator = gen();
        iterator.next();

Copy the code

Promise

Asynchronous programming solutions

Constructors are syntactically used to encapsulate asynchronous operations and can obtain periodic success or failure results

The basic grammar

        // Instantiate the state of the Promise object: initialization succeeds and fails
        const p = new Promise(function (resolve, reject) {
            // Asynchronous operation
            setTimeout(function () {
                // resolve
                // let data = 'user data in database ';
                // resolve(data);

                let err = 'Data read failed';
                reject(err);
            }, 1000);
        });

        The then method that calls the Promise object receives two function type values. The first function type value parameter is successfully called. The second function type value parameter is failed
        p.then(function (value) {
            console.log(value);
        }, function (reason) {
            console.error(reason);
        })
Copy the code

Promise encapsulates the processing of multiple asynchronous tasks that read files

//1. Import fs module
const fs = require('fs');

// Call the method to read the file
     fs.readFile('/ resources for learning. Md'.(err, data) = > {
         // If it fails, an error is thrown
         if (err) throw err;
         // If there is no error, output content
         console.log(data.toString());  // Successful output
    });

//🍎 or use Promise encapsulation
const p = new Promise(function (resolve, reject) {
    fs.readFile('/ resources for learning. Md'.(err, data) = > {
        // Determine if it fails
        if (err) reject(err);
        // If successful
        resolve(data);
    });
});

p.then(function (value) {
    console.log(value.toString());
}, function (reason) {
    console.log("Read failed!!");
});
Copy the code

Promise to encapsulateAJAX

 / / interface address: https://api.apiopen.top/getJoke
        const p = new Promise((resolve, reject) = > {
            //1. Create objects
            const xhr = new XMLHttpRequest();

            / / 2. The initialization
            xhr.open("GET"."https://api.apiopen.top/getJoke");

            / / 3. Send
            xhr.send();

            //4. Bind events and process the response results
            xhr.onreadystatechange = function () {
                / / determine
                if (xhr.readyState === 4) {
                    // Check the response status code 200-299
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // Indicates success
                        resolve(xhr.response);
                    } else {
                        // If it failsreject(xhr.status); }}}})// Specify the callback
        p.then(function (value) {
            console.log(value);
        }, function (reason) {
            console.error(reason);
        });
Copy the code

Promise if-then methods

Whether periodic user data succeeds or fails

Returns the result using p.teng

The then method returns a Promise object whose state is determined by the execution result of the callback function

  1. If the result returned in the callback is a non-Promise property with a status of success, ⭐ returns the object’s success value
    // Create a Promise object
    const p = new Promise((resolve, reject) = > {
      setTimeout(() = > {
        // resolve(' user data ');
        reject('Wrong');
      }, 1000)});The then method returns a Promise object whose state is determined by the result of the callback
    //1. If the result returned in the callback is a non-Promise property with a status of success, ⭐ returns the object's success value

    const result = p.then(value= > {
      console.log(value);
      //1. Non-promise type properties
      // return 'iloveyou';
      //2. Is the promise object
      return new Promise((resolve, reject) = > {
        resolve('ok');
        reject('error');
      });
      //3. Throw an error
      // throw new Error(' Error! ');
      throw 'Wrong! ';
    }, reason= > {
      console.warn(reason);
    });

    // chain call
    p.then(value= > {

    }).then(value= >{});Copy the code

Catch PROMISE is a failed callback syntax sugar that does not specify the first successful function argument and prints the second failed function argument

const p = new Promise((resolve, reject) = >{
            setTimeout(() = >{
                // Set the state of the p object to failure and set the value of failure
                reject("Wrong!);
            }, 1000)});// p.then(function(value){}, function(reason){
        // console.error(reason);
        // });

        p.catch(function(reason){
            console.warn(reason);
        });
Copy the code

The example reads multiple files

                    // Import the fs module
                    const fs = require("fs");

                     // General implementation
                     fs.readFile('/ resources for learning. Md'.(err, data1) = >{
                             fs.readFile('./resources/ md'.(err, data2) = >{
                             fs.readFile('./resources/ books. Md '.(err, data3) = >{
                                 let result = data1 + '\r\n' +data2  +'\r\n'+ data3;
                                 console.log(result);
                             });
                         });
                     });

                // Use the promise implementation
                const p = new Promise((resolve, reject) = > {
                    fs.readFile(". / resources/learn. Md. "".(err, data) = > {
                        resolve(data);
                    });
                });

                p.then(value= > {
                    return new Promise((resolve, reject) = > {
                        fs.readFile("./resources/ transplanting poems. Md".(err, data) = > {
                            resolve([value, data]);
                        });
                    });
                }).then(value= > {
                    return new Promise((resolve, reject) = > {
                        fs.readFile("./resources/ md".(err, data) = > {
                            / / pumped
                            value.push(data);
                            resolve(value);
                        });
                    })
                }).then(value= > {
                    console.log(value.join('\r\n'));
                });

Copy the code

A set is a data structure similar to an array

But the interator interface for member value unique collections can iterate through collection properties and methods using extension operators and for of

1)size Returns the number of elements in the set

2)add adds a new element and returns the current collection

3)delete deletes the element and returns Boolean

4) HAS checks whether the collection contains an element and returns Boolean

        // Declare a set as an array
        let s = new Set(a);let s2 = new Set(['The Big thing'.'Little things'.'Good thing'.'Bad thing'.'Little things']);

        // Number of elements
        console.log(s2.size);/ / 4
        // Add a new element
        s2.add('Happy event');
        // Delete elements
        s2.delete('Bad thing');
        / / testing
        console.log(s2.has('Dregs'));//false
        / / to empty
        s2.clear();
        console.log(s2);/ /"

        for (let v of s2) {
            console.log(v);
        }
Copy the code

case

    let arr = [1.2.3.4.5.4.3.2.1];
        //1. Array decrement
        let result = [...new Set(arr)];
        console.log(result);/ / [1, 2, 3, 4, 5]
        / / 2. The intersection
        let arr2 = [4.5.6.5.6];
        let result = [...new Set(arr)].filter(item= > {
            let s2 = new Set(arr2);/ / 4 5 6
            if (s2.has(item)) {
                return true;
            } else {
                return false; }});/ / or
        let result = [...new Set(arr)].filter(item= > new Set(arr2).has(item));

        / / print
        console.log(result);/ / 4, 5

        / / 3. And set
        let union = [...new Set([...arr, ...arr2])];
        console.log(union);/ / [6]

        //4. Inverse operation of intersection of difference sets
        let diff = [...new Set(arr)].filter(item= >! (new Set(arr2).has(item)));
        console.log(diff);/ / 1, 2, 3
Copy the code

A Map is like an object

A collection of key-value pairs. The key range is not limited to strings, but all types of values (including objects). Map also implements the Interator interface. You can traverse.map properties and methods using the extension operator and for of

1)size Returns the number of map elements

2) Set adds a new element and returns the current map

3) GET returns the key value of the keyname object

4) HAS checks whether the map contains an element and returns Boolean

5) I pay therefore I am

        / / declare the Map
        let m = new Map(a);// Add elements
        m.set('name'.'car');  //Map key:name value: car
        m.set('change'.function () {
            console.log("We can change you!!);//Map key:'change' value f
        });
        let key = {
            school: 'ATGUIGU'
        };
        m.set(key, ['Beijing'.'Shanghai'.'shenzhen']); //key:ATGUIGU value:[' Beijing ', 'Shanghai ',' Shenzhen ']

        //size
        console.log(m.size);/ / 3

        / / delete
        m.delete('name');

        / / to get
        console.log(m.get('change'));//f
        console.log(m.get(key));//[' Beijing ', 'Shanghai ',' Shenzhen ']


        / / to empty
        m.clear();//Map(0)

        // Iterate over each element array
        for (let v of m) {
            console.log(v);
        }

        console.log(m);
Copy the code

Class syntax sugar is more like object-oriented programming syntax

Knowledge:

1) CLSS class declaration

2)constructor defines the constructor initialization

3) Extends extends a parent class

4) Super calls the parent constructor

5)static Defines static methods and properties

6) Superclass methods can be overridden

    / / cell phone
        function Phone(brand, price) {
            this.brand = brand;
            this.price = price;
        }

        // Add method
        Phone.prototype.call = function () {
            console.log("I can call!!");
        }

        // instantiate the object
        let Huawei = new Phone('huawei'.5999);

        console.log(Huawei);//brand:' Huawei 'price:5999 Prototype_proto_ Call method f
        Huawei.call();
        console.log(Huawei)// I can call!! Brand :' Huawei 'Price :5999
        / / 🍎 class
        class Shouji {
            // The constructor word cannot be modified
            constructor(brand, price) {
                this.brand = brand;
                this.price = price;
            }

            The ⭐ method must use this syntax and cannot use ES5's full object form
            call() {
                console.log("I can call!!"); }}let onePlus = new Shouji("1 +".1999);

        console.log(onePlus);//brand:'1+' price:1999 prototype_proto_ call method f


Copy the code

Class static member

    //ES5
        function Phone() {

        }
        Phone.name = 'mobile phone';
        Phone.change = function () {
            console.log("I can change the world");
        }
        Phone.prototype.size = '5.5 inch;

        let nokia = new Phone();

        console.log(nokia.name);// I pay therefore I have no constructor on the instance object
        nokia.change();//is not function
        console.log(nokia.size);/ / 5.5 inch can ⭐

        // ES6
        class Phone {
            // Static attributes
            static name = 'mobile phone';
            static change() {
                console.log("I can change the world"); }}let nokia = new Phone();
        console.log(nokia.name);//underfined
        console.log(Phone.name);/ / cell phone
Copy the code

Object inherits es5 constructor inheritance

     / / cell phone
        function Phone(brand, price) {
            this.brand = brand;
            this.price = price;
        }

        Phone.prototype.call = function () {
            console.log("I can make a call.");
        }

        // Smart phone
        function SmartPhone(brand, price, color, size) {
            Phone.call(this, brand, price);
            this.color = color;
            this.size = size;
        }

        // Sets the prototype of the child constructor
        SmartPhone.prototype = new Phone;
        SmartPhone.prototype.constructor = SmartPhone;

        // Declare the method of the subclass
        SmartPhone.prototype.photo = function () {
            console.log("I can take pictures.")
        }

        SmartPhone.prototype.playGame = function () {
            console.log("I can play games.");
        }

        const chuizi = new SmartPhone('hammer'.2499.'black'.'5.5 inch);

        console.log(chuizi);Price: 2499 size: "5.5-inch" Prototype method child SmartPhone parent phone

Copy the code

Class inheritance

    class Phone {
            // Parent constructor
            constructor(brand, price) {
                this.brand = brand;
                this.price = price;
            }
            // Member attributes of the parent class
            call() {
                console.log("I can call!!"); }}class SmartPhone extends Phone {
            // constructor
            constructor(brand, price, color, size) {
                super(brand, price);// Phone.call(this, brand, price)
                this.color = color;
                this.size = size;
            }

            photo() {
                console.log("Photos"); / / 2. Take photos
            }

            playGame() {
                console.log("Play the game");/ / 3. Play a game
            }

            call() {
                console.log('I can make a video call.'); 1. I can make a video call}}const xiaomi = new SmartPhone('millet'.799.'black'.'4.7 inch);
        console.log(xiaomi);//SmartPhone {brand: 'SmartPhone ', price: 799, color:' black ', size: } subclass constructor=> Class SmartPhone f photo f call
        xiaomi.call();/ / 1
        xiaomi.photo();/ / 2
        xiaomi.playGame();/ / 3
Copy the code

Subclasses deal with class method overrides

If you declare a method with the same name as a subclass, you can’t call a method with the same name as its parent, and you can’t call a method with the same name as its parent using super. Can only be completely rewritten

Class sets and get bind object property methods

     / / get and set
        class Phone {
            get price() {
                console.log("The price attribute was read.");
                return 'iloveyou';
            }

            set price(newVal) {
                console.log('The price attribute has been modified'); }}// instantiate the object
        let s = new Phone();

        console.log(s.price);// The price attribute is read iloveyou
        s.price = 'free';// The price attribute has been modified
Copy the code

Numerical extension

         // 0.number. EPSILON is the minimum precision of JavaScript representation
        / / EPSILON attribute's value is close to 2.2204460492503130808472633361816 e-16
        function equal(a, b) {
            if (Math.abs(a - b) < Number.EPSILON) {
                return true;
            } else {
                return false; }}console.log(0.1 + 0.2= = =0.3);//false
        console.log(equal(0.1 + 0.2.0.3))//true

        //1. Binary and octal
        let b = 0b1010;
        let o = 0o777;
        let d = 100;
        let x = 0xff;
        console.log(x);/ / 255

        //2. Number.isFinite checks whether a Number isFinite
        console.log(Number.isFinite(100));//true
        console.log(Number.isFinite(100 / 0));//false
        console.log(Number.isFinite(Infinity));//false

        //3. number. isNaN checks whether a value isNaN
        console.log(Number.isNaN(123));//false

        //4. number. parseInt number. parseFloat The string is converted to an integer
        console.log(Number.parseInt('5211314love'));/ / 5211314
        console.log(Number.parseFloat('3.1415926 magic'));/ / 3.1415926

        //5. number. isInteger Checks whether a Number is an integer
        console.log(Number.isInteger(5));//true
        console.log(Number.isInteger(2.5));//false

        //6. Math.trunc erases the decimal part of a number
        console.log(Math.trunc(3.5));/ / 3

        Math.sign determines whether a number is positive or negative or zero
        console.log(Math.sign(100));/ / 1
        console.log(Math.sign(0));/ / 0
        console.log(Math.sign(-20000));/ / 1
Copy the code

Object method extension

        🍎 object. is checks whether the two values are exactly equal
        console.log(Object.is(120.120));// true
        console.log(Object.is(NaN.NaN));// true
        console.log(NaN= = =NaN);// false

        //2. 🍎 object. assign Object merge
        const config1 = {
            host: 'localhost'.port: 3306.name: 'root'.pass: 'root'.test: 'test'
        };
        const config2 = {
            host: 'http://atguigu.com'.port: 33060.name: 'atguigu.com'.pass: 'iloveyou'.test2: 'test2'
        }
        console.log(Object.assign(config1, config2));//host: "http://atguigu.com" name: "atguigu.com" pass: "iloveyou" port: 33060test: "test" test2: "test2"

        🍎 object.setProtoTypeof sets the prototype Object object.getPrototypeof
        const school = {
            name: 'car'
        }
        const cities = {
            xiaoqu: ['Beijing'.'Shanghai'.'shenzhen']}Object.setPrototypeOf(school, cities);
        console.log(Object.getPrototypeOf(school));// Xiaoqu: (3) [' Beijing ', 'Shanghai ',' Shenzhen ']
        console.log(school);//name: subclass xiaoqu(3) [' Beijing ', 'Shanghai ',' Shenzhen '] parent class constructor object
Copy the code

ES6 modular

Benefits of taking one large program file, breaking up many small files, and then combining the small files:

1) Prevent naming conflicts

2) Code reuse

3) High maintainability

Modular syntax A method

The export command is used to specify the external interface of a module

The import command is used to input functions provided by other modules

The following methods correspond to m1.js one by one

//🍎
export let school = '123'
export function()
    {
        console.log('234')}//🍎 unified leak
let school = '123'
function find()
    {
        console.log('234')}export {school,find}
//🍎 leaks by default
export default{
    school:'123'
    change:function(){console.log('234')}
Copy the code

html

<script type='module'>
//🍎 common mode
import * as m1 from './m1.js'
console.log(m1)
//🍎 destruct assignment
import {school,change} from './m1.js'
console.log(school)
// The name repeats the 'alias name
import {school as zz,change} from './m1.js'
console.log(zz)
//🍎 default leakage resolved
import {default as m1} from './m1.js'
    ζˆ–
import  m1 from './m1.js'
// This method applies only to default leaks
console.log(m1)
</script>
Copy the code

Es6 Module B

app.js


// Module import '
import * as m1 from './m1.js'


/ / use jsm1.change(); .Copy the code

html

<script src='./app.js type='module' />
Copy the code

Resolve compatibility projects to adopt es5 mode

1. Installation tool babel-cli babel-preset-env Browserify (or webpack) Packaging tool -D

2.npx babel src/js dist/js –presets=babel-preset-env

NPX Browserify dist/js/app.js -o dist/bundle.js

HTML error

<script src="/dist/js/app.js"/>
Copy the code

correct

<script src="dist/bundle.js"/>
Copy the code

4. Keep packing

The case uses JQ to change the background color

  1. npm i jquery

2.app.js

import $ from 'jquery'
// Use the jQ code normally.Copy the code

Pack 3.

ES7

Array.prototypr.includes

The array method checks whether an array contains an element and returns a Boolean value

        // includes indexOf
        const mingzhu = [Journey to the West.A Dream of Red Mansions.Romance of The Three Kingdoms.'Water Margin'];

        / / determine
        console.log(mingzhu.includes(Journey to the West));//true
        console.log(mingzhu.includes('Golden Bottle plum'));//false
Copy the code

Exponential operator

The exponential operator ** is introduced to implement the same exponentiation function as math.pow

        / / * *
        console.log(2 ** 10);/ / 1024
        console.log(Math.pow(2.10));/ / 1024
Copy the code

ES8

Async and await

To solve the asynchronous

Async function

The async function returns a promise object

The result of the Promise object is determined by the return value executed by the async function

        / / async function
        async function fn() {🍎 returns a string// return '车车';/ Not one result is returnedPromiseType, and the return result is successPromiseobject// return;🍎 throws an error and returns a failed resultPromise
            // throw new Error(' Error! ');
            
            
            // Return a Promise object
            return new Promise((resolve, reject) = > {
                resolve('Success data');//🍎 successful data
                // reject(" reject error ");
            });
        }

        const result = fn();

        // Call the then method
        result.then(value= > {
            console.log(value);
        }, reason= > {
            console.warn(reason);
        })
Copy the code

Await the expression

Await must be written in async function

The expression to the right of await is usually a Promise object

Await returns the promise success value

An await promise fails and an exception is thrown that needs to be caught and handled with a try catch

Create a Promise objectconst p = new Promise((resolve, reject) = > {
            resolve("User Data");
            // reject(" Reject!") ); // A try catch is required
        })

        // await to be placed in async function.
        async function main() {
            try {
                let result = await p;
                //
                console.log(result);
            } catch (e) {
                console.log(e); }}// Call the function
        main();
Copy the code

Read multiple files in combination

    //1. Import fs module
const fs = require("fs");

// Read "for learning"
function readWeiXue() {
    return new Promise((resolve, reject) = > {
        fs.readFile(". / resources/learn. Md. "".(err, data) = > {
            // If it fails
            if (err) reject(err);
            // If successfulresolve(data); })})}function readChaYangShi() {
    return new Promise((resolve, reject) = > {
        fs.readFile("./resources/ transplanting poems. Md".(err, data) = > {
            // If it fails
            if (err) reject(err);
            // If successfulresolve(data); })})}function readGuanShu() {
    return new Promise((resolve, reject) = > {
        fs.readFile("./resources/ md".(err, data) = > {
            // If it fails
            if (err) reject(err);
            // If successfulresolve(data); })})}Declare an async function
async function main(){
    // Get
    let weixue = await readWeiXue();
    // Get the content of rice transplanting poem
    let chayang = await readChaYangShi();
    // Get a sense of the book
    let guanshu = await readGuanShu();

    console.log(weixue.toString());
    console.log(chayang.toString());
    console.log(guanshu.toString());
}

main();
Copy the code

Used in combination to encapsulate Ajax requests

    // Send an AJAX request that returns a Promise object
        function sendAJAX(url) {
            return new Promise((resolve, reject) = > {
                //1. Create objects
                const x = new XMLHttpRequest();

                / / 2. The initialization
                x.open('GET', url);

                / / 3. Send
                x.send();

                //4. Event binding
                x.onreadystatechange = function () {
                    if (x.readyState === 4) {
                        if (x.status >= 200 && x.status < 300) {
                            / / success
                            resolve(x.response);
                        }else{
                            // If it failsreject(x.status); }}}})}// Test the promise then method
             sendAJAX("https://api.apiopen.top/getJoke").then(value= >{
                 console.log(value);
            }, reason= >{})
  
        // async and await test axios
        async function main(){
            // Send an AJAX request
            let result = await sendAJAX("https://api.apiopen.top/getJoke");
            // Test again
            let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P')

            console.log(tianqi);
        }

        main();
Copy the code

Object methods extend objext. values and Object.entries

The objext.values () method returns an array of all enumerable property values for a given object

The object.entries () method returns an array of the given Object’s own traversable property [key,vakue]

Object.getOwnPropertyDescriptors

This method returns a description object for all of the specified object’s own properties


    // Declare objects
        const school = {
            name: "Car".cities: ['Beijing'.'Shanghai'.'shenzhen'].xueke: ['front end'.'Java'.'Big Data'.'operations']};// Get all the keys of the object
        console.log(Object.keys(school));//Array(3) 0: "name" 1: "cities" 2: "xueke"
        // Get all the values of the object
        console.log(Object.values(school));/ / : "car" 1: Array (3) 0: "Beijing" 1: "Shanghai" 2: "shenzhen" length: 3 [[Prototype]] : Array (0) 2: Array (4) 0: "front end" 1: "Java" 2:3: "big data" "Operations"
        //entries
        console.log(Object.entries(school));/ / key values
        / / create a Map
        const m = new Map(Object.entries(school));
        console.log(m.get('cities'));//[' Beijing ', 'Shanghai ',' Shenzhen '],

        // The object attributes describe the object
        console.log(Object.getOwnPropertyDescriptors(school));//Object school cites xueke
        // create the first prototype object and the second description object
        const obj = Object.create(null, {
            name: {
                / / set the value
                value: 'car'.// Attribute attributes
                writable: true.configurable: true.enumerable: true}});Copy the code

ES9

Rest parameters for objects with extensions and operators


    // Rest parameters are stored in user
        function connect({ host, port, ... user }) {
            console.log(host);/ / 127.0.0.1
            console.log(port);/ / 3306
            console.log(user);
        }

        connect({
            host: '127.0.0.1'.port: 3306.username: 'root'.password: 'root'.type: 'master'
        });


        // Object merge parses out merge
        const skillOne = {
            q: 'Sky sound'
        }

        const skillTwo = {
            w: 'Golden bell jar'
        }

        const skillThree = {
            e: 'Thunder in the sky'
        }
        const skillFour = {
            r: 'The Dragon wags its tail'
        }

        constmangseng = { ... skillOne, ... skillTwo, ... skillThree, ... skillFour };console.log(mangseng)

        / /... SkillOne => Q: 'Skywave ', W:' Golden Bell Jar '
Copy the code

The regular extension names capture groups

Add attributes to the captured results to facilitate extraction

        // Declare a string
        let str = ';

        // // Extract URL and "tag text"
        const reg = /<a href="(.*)">(.*)<\/a>/;

        / / / / execution
        const result = reg.exec(str);

        console.log(result);//
        console.log(result[1]);//http://www.atguigu.com
        console.log(result[2]);/ / car


        let str = ';
        // // Group naming
        const reg = /(? 
       
        .*)<\/a>/
       ;

        const result = reg.exec(str);

        console.log(result.groups.url);//http://www.atguigu.com

        console.log(result.groups.text);/ / car
Copy the code

Regular extension reverse assertion

Check whether the matching result is correct

        // Declare a string
        let str = 'JS5211314 Do you know 555 la la la la ';
        // The forward assertion number extracts 555
        // const reg = /\d+(? =) /;
        // const result = reg.exec(str);

        // Reverse assertion makes a judgment based on the previous content
        const reg = / (? < =?) \ d + /;
        const result = reg.exec(str);
        console.log(result);
Copy the code

Regular extension dotAll pattern

        // dot. metacharacter Any single character other than a newline
        let str = ` < ul > < li > < a > shoven grams of redemption < / a > < p > release date: 1994-09-10 < / p > < / li > < li > < a > forrest gump < / a > < p > release date: 1994-07-06 < / p > < / li > < / ul > `;
        // Declare the regular movie name Β· and release time extracted
        const reg = /
  • \s+(.*?) <\/a>\s+

    (.*?) <\/p>/

  • ; ⭐⭐⭐ or Dotall mode g global matchconst reg = /
  • .*? (.*?) <\/a>.*?

    (.*?) <\/p>/g

  • s; // Perform a match // const result = reg.exec(str); let result; let data = []; while (result = reg.exec(str)) { data.push({ title: result[1].time: result[2]}); }// Output the result console.log(data);//Array(2) 0: {title: 'Shoshank ', time:' uanjing '} 1: {title: 'Forrest Gump ', time:' Uanjing '} Copy the code

    ES10

    Object.fromEntries

    Create an object that receives a two-dimensional array map

        // Two dimensional array key values
            const result = Object.fromEntries([
                ['name'.Silicon Valley],
                ['xueke'.'Java, Big Data, front-end, Cloud Computing ']]);console.log(result);// "Xueke" xueke: "Java, big data, front-end, cloud computing"
    
    
            //Map // Convert two-dimensional arrays into objects
            const m = new Map(a); m.set('name'.'ATGUIGU');
            const result = Object.fromEntries(m);
            console.log(result);//Object name: "ATGUIGU"
            // object. entries ES8 convert objects into two-dimensional arrays
            const arr = Object.entries({
                name: Silicon Valley
            })
            console.log(arr); //Array(1)=>0: Array(2) 0: "name" 1: "name"
    Copy the code

    TrimStar and trimEnd

            let str = ' iloveyou ';
    
            console.log(str);// iloveYou leave blank
            console.log(str.trimStart());// iloveyou clear left
            console.log(str.trimEnd());// iloveyou clear right
    Copy the code

    Flat and flatMap

            / / flat
            // Convert a multidimensional array to a lower-dimensional array
            const arr = [1.2.3.4[5.6]].console.log(arr.flat());//[1, 2, 3, 4,5, 6];
            const arr = [1.2.3.4[5.6[7.8.9]]];
            // The depth is a numeric variable in one dimension
            console.log(arr.flat(2));//[1, 2, 3, 4, 5, 6,7, 8, 9]
    
            //flatMap Results in a reduced dimension
            const arr = [1.2.3.4];
            const result = arr.map(item= > item * 10);
            console.log(result);/ /,20,30,40 [10]
            
            // The return is [10] [20] [30] [40] below the array
            const result = arr.flatMap(item= > [item * 10]);
            console.log(result); //Array(4) 0: 10 1: 20 2: 30 3: 40
    Copy the code

    Symbol.prototype.description

    Gets the symbol description string

            / / create a Symbol
            let s = Symbol(Silicon Valley);
    
            console.log(s.description);/ / is still silicon valley
    Copy the code

    ES11

    Private property

         class Person {
                // Public attributes
                name;
                // Private attribute flag #
                #age;
                #weight;
                // Constructor initialization
                constructor(name, age, weight) {
                    this.name = name;
                    this.#age = age;
                    this.#weight = weight;
                }
    
                intro() {
                    console.log(this.name);/ / XiaoHong
                    console.log(this.#age);/ / 18
                    console.log(this.#weight);//45kg
                }
            }
             girl.intro();  //⭐ calls print above
            / / instantiate
            const girl = new Person('XiaoHong'.18.'45kg');
    
            console.log(girl.name);/ / XiaoHong
            console.log(girl.#age);// An error occurs that external private attributes cannot be accessed
            console.log(girl.#weight);// An error occurs that external private attributes cannot be accessed
    
           
    Copy the code

    Promise.allSettled

    Receives the Promise array and returns the resulting Promise object

    Every asynchronous task wants results using promise.allSettled

    Require each asynchronous task to succeed to continue execution with promise.all

            // Declare two Promise objects
            const p1 = new Promise((resolve, reject) = > {
                setTimeout(() = > {
                    resolve('Commodity Data - 1');
                }, 1000)});const p2 = new Promise((resolve, reject) = > {
                setTimeout(() = > {
                    //resolve(' commodity data - 2');
                    reject('Wrong! ');
                }, 1000)});Copy the code
        // Call the allSettled method
            const result = Promise.allSettled([p1, p2]);
            console.log(result);
    Copy the code

            const res = Promise.all([p1, p2]);
    
            console.log(res);
    Copy the code

    The difference between

    String.prototype.matchAll

    The character pass extension method is used to get regular batch matching results ⭐⭐⭐ utility

         // Need to extract the name and release date of each movie
            let str = ` < ul > < li > < a > shoven grams of redemption < / a > < p > release date: 1994-09-10 < / p > < / li > < li > < a > forrest gump < / a > < p > release date: 1994-07-06 < / p > < / li > < / ul > `;
    
            // Declare the re
            const reg = /
  • .*? (.*?) <\/a>.*?

    (.*?) <\/p>/

  • sg // Call the method const result = str.matchAll(reg); Copy the code
        // The first way
            for (let v of result) {
                console.log(v);
            }
    Copy the code

         // The second way
            const arr = [...result];
    
            console.log(arr);
    Copy the code

    Optional chain operator

    ? . Combined use

    The object hierarchy is deep when dealing with object type parameters

            // Pass in the object
            function main(config) {
                1.
                const dbHost = config && config.db && config.db.host;
                console.log(dbHost);/ / ⭐ 192.168.1.100
                
                // Two ways
                
                2.Optional chain operatorconstdbHost = config? .db? .host;console.log(dbHost);/ / ⭐ 192.168.1.100
            }
    
            main({
                db: {
                    host: '192.168.1.100'.username: 'root'
                },
                cache: {
                    host: '192.168.1.200'.username: 'admin'}})Copy the code

    Dynamic import

    hello.js

        export function hello(){
        alert('Hello');
    }
    Copy the code

    app.js

    const btn = document.getElementById('btn');
    
    btn.onclick = function(){
        import('./hello.js').then(module= > {
            module.hello();
        });
    }
    Copy the code

    Introduction of HTML

    <body>
        <button id="btn">Click on the</button>
        <script src="./js/app.js" type="module"></script>
    </body>
    Copy the code

    bigint

            / / big plastic
            let n = 521n;
            console.log(n, typeof (n));//521n 'bigint'
    
            / / function
            // let n = 123;
            console.log(BigInt(n)); //521n
            console.log(BigInt(1.2));Uncaught RangeError: The number 1.2 cannot be converted to a BigInt because it is not an integer
    
            // Large numeric operations
            let max = Number.MAX_SAFE_INTEGER;
            console.log(max);   / / 9007199254740991
            console.log(max + 1);   / / 9007199254740992
            console.log(max + 2);   / / 9007199254740992
    
            console.log(BigInt(max))    //9007199254740991n
            console.log(BigInt(max) + BigInt(1)) //9007199254740992n
            console.log(BigInt(max) + BigInt(2))  //9007199254740993n
    Copy the code

    GlobalThis operates on global objects regardless of the operating environment

    This global

    Always point to a global object no matter what the execution environment is, okay

    html

        <body>
        <script>
            console.log(globalThis);  // Points to the window object
        </script>
    </body>
    Copy the code

    Js run code Runs the JS file

    console.log(globalThis); / / points to global
    Copy the code