ES6 key knowledge summary

Keywords: Javascript html5 Vue.js

The most important and complex knowledge points of ES6: 1. Class and inheritance 2.promise 3. ES6 modularization (in vue)

Knowledge points related to deep copy

  1. Object.assgin() method: it can realize the deep copy of the first layer object
  2. Simple and crude deep copy

JSON.parse(JSON.stringify(obj))
  1. Complete deep copy: refer to online materials

Common array methods

The following methods have callback functions. The two formal parameters of the callback are item value and index respectively
return is required for all methods except forEach

  1. arr.forEach()
  2. arr.map()
  3. arr.filter()
  4. arr.some()
  5. arr.every()
  6. arr.reduce()

let: declare block level scope

  • There is no problem of declaration in advance
  • Declaration cannot be repeated in the same block
  • The correct index can be obtained through let

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

const: declare constants

  • const is also a block level scope
  • Assignment is required at the same time of declaration

Arrow function

arr.forEach(()=>{})
setInterval(()=>{},1000)

let fun = ()=>{}
let fun = x => {}
let fun = (x,y) => {}
let fun = (x,y) => 3
let fun = (x,y) => ({
        name: 1,
        age: 2
    })

this of the arrow function points to

The arrow function itself does not have this. Its internal this is the this that defines the environment where the arrow function is located

        box.onclick = function(){
            // console.log(this);
            let i  = 0
            setInterval(()=>{
                this.innerHTML = i;  //this is box
                i++
            },1000)
        }

Shorthand for object literals

    let color = 'red',
        age = 18;

    let obj = {
        color,
        age,
        run(){
            console.log('run')
        }
    }

Classes and inheritance

Define parent class

class Animal {
    constructor(color){
        this.type = 'animal';
        this.eye = true;
        this.color = color;
    }
    sound(){
        console.log('sound')
    }
}

var ani = new Animal('red')

Define subclasses

class Cat extends Animal{
    constructor(nickname,age,color){
        super(color);
        this.nickname = nickname;
        this.age = age;
    }
    eat(){
        console.log('eat')
    }
}
var cat = new Cat('little cat',5,'white')
cat.sound()

Template string

    let color = 'red';
    let str = `this is ${color}`

Destructuring assignment

    let obj = {
            title: 'aaaa',
            price: 300,
            discount: 200
        }

    let {title,price} = obj;

Expand operator

Break up the values in the array and list them one by one

        let arr = [34, 56, 78];

        function total(Ch, En, Math) {
            return Ch + En + Math;
        }
        let result = total(...arr)

        let divList = document.querySelectorAll("div");

        //A pseudo array can call forEach, but cannot call the traversal methods of other arrays
        divList.forEach((el)=>{
            console.log(el);
        })

        var arr = [...divList].map((el)=>{
            return el.innerHTML
        })
        console.log(arr);

Default parameters

        function draw(radius=100){
            console.log(radius);
        }
        draw(30)

        // The default parameter must be set last
        function draw(y,x=2,z=20){
            console.log(x,y,z);
        }

        draw(1)
        draw(1,3)

Remaining parameters

        function total(...args){
            console.log(args);
            console.log(args instanceof Array);  //true
        }
        total(23,45)

Symbol data type

The only variable that will not be repeated is the basic data type added in ES6

        // Application scenario of Symbol

        //An object is defined in a third-party library (hidden to users)

        let obj = {
            name: '23',
            count() {
                console.log('count');
            }
        }

        // Extend the function of the object: you want to use an attribute name that will not duplicate the existing attributes of the object

        let count = Symbol();

        obj[count] = function(){
            console.log('quantity');
        }

        obj.count()  // count
        obj[count]();  //quantity

Data of type Set

Is the data type of the collection newly added in ES6, which is used to store arrays. However, the elements of an array cannot be repeated

Array de duplication

    var arr = [1,2,3,2,5,1]
    var result = [...new Set(arr)]
    console.log(result);

Set common API s

        1. add
        2. delete
        3. has
        4. clear

for...of statement

  • for: (1) you need to specify the number of traversals; (2) you can't traverse the object, you can traverse the collection array other than the object, and the pseudo array (3) you can use break and continue
  • forEach: (1) you can traverse collections other than objects (array, set, NodeList - > DOM Collection) (2) you cannot use break and continue
  • for...in (1) traverses the object (2) cannot directly access the attribute value of the object (3) (3) break and continue can be used
  • New for...of:
    (1) for...of cannot be used for custom objects, but most native data sets can be used (array, string, Set type, Map type, NodeList)
    (2) You can use break and continue

    //Act on array
    var arr = ['a','c','d']
        for(let i of arr){
            console.log(i);
        } 

//NodeList acting on element node
    let divList = document.querySelectorAll("div");
        for (let el of divList){
            console.log(el);
        }

Object API

  1. Object.assign: merge objects
  2. Object.keys(): returns a collection of all keys of an object

        let obj = {
            name: 'Peppa',
            age: 4,
            sex: 'female'
        }
        // ["name","age","sex"]
        console.log(Object.keys(obj));

Map type data

Similar to an object, it is used to store key value pairs.

Objects can only use strings as attribute names, while maps can use any type of data as attribute names

//The first key is "a" with a value of 1, and the second key is b with a value of 2
        var map1 = new Map([["a",1],["b",2]]);
        console.log(map1);

API for Map

        attribute: size 
        method: set , get , has, delete ,clear

for...of traversal

    var map1 = new Map([["a", 1], ["b", 2]]);
        
        //Traverse keys only
        for (let key of map1.keys()){
            console.log(key);
        }

        // Traversal values only
        for (let val of map1.values()){
            console.log(val);
        }


        // val is an array that stores the key and value of each
        for (let val of map1){
            console.log(val[0]);
            console.log(val[1]);
        }

        //Return key value pairs at the same time
        for (let [key,value] of map1){
            console.log(key);
            console.log(value);
        }

        // Equivalent to the above writing
        for (let [key,value] of map1.entries()){
            console.log(key);
            console.log(value);
        }

Promise:

  • promise is used to solve the problem of callback hell and implement asynchronous code in a synchronous way

  • Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions - callback functions and events.
    It was first proposed and implemented by the community. ES6 has written it into the language standard, unified the usage, and provided Promise objects natively.

  • Three states of a Promise
    pending: initial state, which is neither successful nor failed.
    Fully: indicates that the operation completed successfully.
    rejected: means the operation failed.

  • The Promise constructor accepts a function as an argument. The two parameters of the function are resolve and reject. They are two functions provided by the JavaScript engine and do not need to be deployed by themselves.
    The Resolve function is used to change the state of the Promise object from "incomplete" to "successful" (that is, from pending to resolved), call it when the asynchronous operation is successful, and pass the result of the asynchronous operation as a parameter;
    The Reject function is used to change the state of the Promise object from incomplete to failed (that is, from pending to rejected), call it when the asynchronous operation fails, and pass the error reported by the asynchronous operation as a parameter.

  • After the Promise instance is generated, you can use the then method to specify the callback functions in the resolved state and the rejected state respectively.

    ```
        // Requirements: execute ajax2 after ajax1 is executed, and task after ajax2 is executed
        function ajax1() {
            setTimeout(function () {
                console.log('ajax1');
            }, 1000)
        }
        function ajax2() {
            setTimeout(function () {
                console.log('ajax2');
            }, 2000)
        }
        function task() {
            console.log('task');
        }
    ```

Implemented with Promise

       var flag1 = true;
       var flag2 = false;

       function error(err) {
           console.log(err);
       }
       function ajax1() {
           return new Promise((resolve, reject) => {
               setTimeout(function () {
                   if (flag1) {
                       resolve('ajax1 Results')
                   } else {
                       reject('ajax1 error')
                   }
               }, 1000)
           })
       }

       function ajax2(data) {
           return new Promise((resolve, reject) => {
               setTimeout(function () {
                   console.log('ajax2 receive ajax1 Parameters of', data);
                   if (flag2){
                       resolve()
                   }else{
                       reject('ajax2 error')
                   }
               }, 2000)
           })
       }

       function task() {
           console.log('task');
       }

       ajax1()
           .then(ajax2)
           .then(task)
           .catch(error)

Promise.all() Promise.race()

Promise.all() the logic to execute after both asynchronous operations are successfully completed
Promise.race() the asynchronous operation that gets the result first is executed successfully, that is, the following logic is executed
Parameters in all() and race() must be promise instances

   Promise.all([ajax1(),ajax2()])
           .then(function(data){
               console.log('Data after both requests are successful',data);
               task(data)
           })
           .catch(err)

   Promise.race([ajax1(), ajax2()])
           .then(function (data) {
               console.log('Request to return the result of the fastest task', data);
               task(data)
           })
           .catch(err)

Usage of async and await

  • async: define an asynchronous function, eliminate the chain call of then in promise, and make the code clearer and elegant
  • await is followed by a function that returns new promise and executes it
  • await can only be placed in async functions
  • The async function handles the logic to be executed in case of failure through try...catch

    var flag1 = false;
        var flag2 = true;
        function ajax1() {
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    console.log('ajax1 The task is completed');
                    if (flag1) {
                        resolve('ajax1 Results')
                    } else {
                        reject('ajax1 error')
                    }
                }, 1000)
            })
        }
        function ajax2(data) {
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    console.log('ajax2', data);
                    console.log('ajax2 The task is completed');
                    if (flag2) {
                        resolve('ajax2 Results')
                    } else {
                        reject('ajax2 error')
                    }
                }, 2000)
            })
        }
        function task(data) {
            console.log('task The task is completed');
            console.log('task', data);
        }
       

        async function render() {
            try {
                let result1 = await ajax1()
                await ajax2(result1)
                task()
            }catch(err){
                console.log('catch',err);
            }
        }
        render()

Object.defineProperty()

Define the properties of the object

let obj = {
    name: 'Journey to the West',
    addTime: '739754975945489'
}

//You must use a temporary variable to store the value of the name attribute
let temp = obj.name;


// Interceptor
Object.defineProperty(obj,"name",{
    //Accessor
    get: function(){
        console.log('get');
        //There must be a return in get. The result of return is the new value of the name attribute
        return "<" + temp + ">"
    },
    set: function(newVal){
        console.log('set');
        temp = newVal;
    }
})

obj.name = "Bean by the window";
console.log(obj.name);


 

Posted by WindomEarle on Wed, 06 Oct 2021 22:32:36 -0700